Android 仿滑动解锁控件

自定义类

public class LoadAwaySlideUnlockView extends View {
    public interface UnlockListener {
        void onLoadAwayUnlock();
    }

    private UnlockListener mUnlockListener;


    public void setUnlockListener(UnlockListener unlockListener) {
        mUnlockListener = unlockListener;
    }

    private static final int MSG_REDRAW = 1;
    private static final int DRAW_INTERVAL = 50;
    private static final int STEP_LENGTH = 10;//速度

    private Paint mPaint;//文字的画笔
    private Paint mSliPaint;//滑块画笔
    private Paint mBgPaint;//背景画笔
    private Paint mBluePaint;//划过去之后蓝色背景的画笔

    private VelocityTracker mVelocityTracker;//滑动速度
    private int mMaxVelocity;
    private LinearGradient mGradient;//渐变色
    private LinearGradient bgGradient;//背景渐变色
//    private LinearGradient sliGradient;//滑块渐变色
//    LinearGradient有两个构造函数;
//
//    public LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions,Shader.TileMode tile)
//
//    参数:
//
//    float x0: 渐变起始点x坐标
//
//    float y0:渐变起始点y坐标
//
//    float x1:渐变结束点x坐标
//
//    float y1:渐变结束点y坐标
//
//    int[] colors:颜色 的int 数组
//
//    float[] positions: 相对位置的颜色数组,可为null,  若为null,可为null,颜色沿渐变线均匀分布
//
//    Shader.TileMode tile: 渲染器平铺模式
//
//
//
//    public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1,Shader.TileMode tile)
//
//    float x0: 渐变起始点x坐标
//
//    float y0:渐变起始点y坐标
//
//    float x1:渐变结束点x坐标
//
//    float y1:渐变结束点y坐标
//
//    int color0: 起始渐变色
//    int color1: 结束渐变色
//
//    Shader.TileMode tile: 渲染器平铺模式

    private int[] mGradientColors;
    private int[] bgGradientColors;
    private int mGradientIndex;
    private Interpolator mInterpolator;
    private float mDensity;
    private Matrix mMatrix;
    private ValueAnimator mValueAnimator;


    private int width;
    private int height;

    private String mText;//文字
    private int mTextSize;//文字大小
    private int mTextLeft;//文字距离左边
    private int mR;//滑块的半径
    private float margin;


    private Rect mSliderRect;
    private int mSlidableLength;    // SlidableLength = BackgroundWidth - LeftMagins - RightMagins - SliderWidth
    private int mEffectiveLength;   // Suggested length is 20pixels shorter than SlidableLength
    private float mEffectiveVelocity = 1000;//滑块自动回滚的速度

    private float mStartX;
    private float mStartY;
    private float mLastX;
    private float mMoveX;

    public LoadAwaySlideUnlockView(Context context) {
        this(context, null);
    }

    public LoadAwaySlideUnlockView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadAwaySlideUnlockView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public void setText(String text){
        mText = text;

    }

    public LoadAwaySlideUnlockView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mDensity = getResources().getDisplayMetrics().density;
        ViewConfiguration configuration = ViewConfiguration.get(context);
        mMaxVelocity = configuration.getScaledMaximumFlingVelocity();
        mInterpolator = new AccelerateDecelerateInterpolator();

        setClickable(true);
        setFocusable(true);
        setFocusableInTouchMode(true);

        mSlidableLength = 200;
        mTextSize = 30;//文字大小
        mTextLeft = 10;//文字距离左边
        mMoveX = 0;
        mGradientIndex = 0;

        mSliPaint = new Paint();
        mSliPaint.setColor(Color.parseColor("#4a4c5b"));
        mSliPaint.setAntiAlias(true);

        mBgPaint = new Paint();
        mBgPaint.setColor(Color.parseColor("#a6a6a6"));
        mBgPaint.setAntiAlias(true);


        mBluePaint = new Paint();
        mBluePaint.setColor(Color.parseColor("#009496"));
        mBluePaint.setAntiAlias(true);


        mPaint = new Paint();
        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(mTextSize);
        //该方法即为设置基线上那个点究竟是left,center,还是right
        mPaint.setTextAlign(Paint.Align.LEFT);
        //  mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int specWidthSize = MeasureSpec.getSize(widthMeasureSpec);//宽
        int specHeightSize = MeasureSpec.getSize(heightMeasureSpec);//高

        mMatrix = new Matrix();

        width = specWidthSize;
        height = specHeightSize;
        mTextLeft = (int) (height * 1.5);
        margin = height / 20;
        mR = (int) (((height-margin*2) / 2)-margin);


        //最大滑动距离
        mSlidableLength = (int) (specWidthSize -(mMoveX+mR*3+margin*3-mMoveX+margin));
        //有效距离
        mEffectiveLength = mSlidableLength-20;


        mSliderRect=new Rect((int)margin, (int)margin, 300, (int)(height - margin));


        mGradientColors = new int[]{Color.argb(255, 120, 120, 120),
                Color.argb(255, 120, 120, 120), Color.argb(255, 255, 255, 255)};



        mGradient = new LinearGradient(0, 0, width/2, 0, mGradientColors,
                new float[]{0, 0.7f, 1}, Shader.TileMode.MIRROR);



        bgGradient = new LinearGradient(
                0, 0, 0, (float) ((height)/2.0),
                Color.argb(80, 0X77, 0X77, 0X77), Color.argb(200, 0X11, 0X11, 0X11),
                Shader.TileMode.CLAMP
        );

        mHandler.removeMessages(MSG_REDRAW);
        mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //背景色
        RectF oval = new RectF(margin, margin, width - margin, height - margin);// 设置个新的长方形
        canvas.drawRect(oval,mBgPaint);


        //划过去背景色
        RectF ovalBlue= new RectF(margin,margin,mMoveX+margin,mR*2+margin*3);
        canvas.drawRect(ovalBlue,mBluePaint);

        //文字
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float top = fontMetrics.top;//为基线到字体上边框的距离
        float bottom = fontMetrics.bottom;//为基线到字体下边框的距离
        int baseLineY = (int) (height / 2 - top / 2 - bottom / 2);//基线中间点的y轴计算公式
        canvas.drawText(mText, mTextLeft, baseLineY, mPaint);



        //滑块
        RectF oval2 = new RectF(mMoveX+margin,margin,mMoveX+mR*3+margin*3,mR*2+margin*3);// 设置个新的长方形
        canvas.drawRect(oval2,mSliPaint);//方形


        //三个小箭头
        Bitmap bitmap = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.z_icon_right);
        canvas.drawBitmap(bitmap,mMoveX+(mMoveX+mR*3+margin*3-mMoveX)/2-15,mR-margin,mSliPaint);
        canvas.drawBitmap(bitmap,mMoveX+(mMoveX+mR*3+margin*3-mMoveX)/2,mR-margin,mSliPaint);
        canvas.drawBitmap(bitmap,mMoveX+(mMoveX+mR*3+margin*3-mMoveX)/2+15,mR-margin,mSliPaint);




    }

    public void reset() {
        if (mValueAnimator != null) {
            mValueAnimator.cancel();
        }
        mMoveX = 0;
        mPaint.setAlpha(255);

        mHandler.removeMessages(MSG_REDRAW);
        mHandler.sendEmptyMessageDelayed(MSG_REDRAW,200);
    }




    @Override
    public boolean onTouchEvent(MotionEvent event) {

//        Log.e(event.getAction()+"");
        // 点击是否在滑块上
        if (event.getAction() != MotionEvent.ACTION_DOWN
                && !mSliderRect.contains((int) mStartX, (int) mStartY)) {
            if (event.getAction() == MotionEvent.ACTION_UP
                    || event.getAction() == MotionEvent.ACTION_CANCEL) {
                mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL);
            }
            return super.onTouchEvent(event);
        }
        acquireVelocityTrackerAndAddMovement(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mStartX = event.getX();
                mStartY = event.getY();
                mLastX = mStartX;
                mHandler.removeMessages(MSG_REDRAW);
//                L.e("按下");
                Log.e("SlideU","按下");

                break;

            case MotionEvent.ACTION_MOVE:
                Log.e("SlideU","移动");

                mLastX = event.getX();
                if (mLastX > mStartX) {
                    if (mLastX - mStartX > mSlidableLength) {
                        mLastX = mStartX + mSlidableLength;
                        mMoveX = mSlidableLength;
                    } else {
                        mMoveX = (int) (mLastX - mStartX);
                    }
                } else {
                    mLastX = mStartX;
                    mMoveX = 0;
                }
                invalidate();
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                Log.e("SlideU","超出或抬起");
                mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity);
                float velocityX = mVelocityTracker.getXVelocity();
                Log.e("SlideU","速度"+velocityX);
                if (mLastX - mStartX > mEffectiveLength || velocityX/2 > mEffectiveVelocity) {
                    startAnimator(mLastX - mStartX,  mSlidableLength, velocityX, true);
                } else {
                    startAnimator(mLastX - mStartX,  0, velocityX, false);
                    mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL);
                }
                releaseVelocityTracker();
                break;
        }
        return super.onTouchEvent(event);
    }

    private void startAnimator(float start, float end, float velocity, boolean isRightMoving) {
        if (velocity < mEffectiveVelocity) {
            velocity = mEffectiveVelocity;
        }
        int duration = (int) (Math.abs(end - start) * 1000 / velocity);
        mValueAnimator = ValueAnimator.ofFloat(start, end);
        mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mMoveX = (Float) animation.getAnimatedValue();
                invalidate();
            }
        });
        mValueAnimator.setDuration(duration);
        mValueAnimator.setInterpolator(mInterpolator);
        if (isRightMoving) {
            mValueAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
//                    L.e("解锁");
                    Log.e("SlideU","解锁");

                    if (mUnlockListener != null) {
                        mUnlockListener.onLoadAwayUnlock();
                    }
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
        }
        mValueAnimator.start();
    }

    private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);
    }

    private void releaseVelocityTracker() {
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
    }





    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_REDRAW:
                    if(mMatrix==null){
                        mMatrix = new Matrix();

                    }
                    mMatrix.setTranslate(mGradientIndex, 0);

                    if(mGradient==null){
//                        L.e("mGradient空");
                        mGradientColors = new int[]{Color.argb(255, 120, 120, 120),
                                Color.argb(255, 120, 120, 120), Color.argb(255, 255, 255, 255)};

                        mGradient = new LinearGradient(0, 0, width/2, 0, mGradientColors,
                                new float[]{0, 0.7f, 1}, Shader.TileMode.MIRROR);
                    }

                    mGradient.setLocalMatrix(mMatrix);
                    invalidate();
                    mGradientIndex += STEP_LENGTH ;
                    if(mGradientIndex>=Integer.MAX_VALUE){
                        mGradientIndex = 0;
                    }
                    mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL);
                    break;
            }
        }
    };
}

xml界面中引用

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout_close"
    tools:context=".close.CloseActivity">

    <com.aiyouxiba.closescreendemo.view.LoadAwaySlideUnlockView
        android:layout_width="match_parent"
        android:layout_height="56dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:id="@+id/open_view"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

activity使用

        openView = (LoadAwaySlideUnlockView) findViewById(R.id.open_view);
  
        openView.setText("滑动解锁");

        openView.setUnlockListener(new LoadAwaySlideUnlockView.UnlockListener() {
            @Override
            public void onLoadAwayUnlock() {
                Log.e("TAG", "onLoadAwayUnlock: 滑动" );
                finish();
            }
        });

原链接:https://blog.csdn.net/smallredzi/article/details/105264135

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,372评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,368评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,415评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,157评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,171评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,125评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,028评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,887评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,310评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,533评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,690评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,411评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,004评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,812评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,693评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,577评论 2 353

推荐阅读更多精彩内容