android实现滑动解锁

本文实例为大家分享了android实现滑动解锁的具体代码,供大家参考,具体内容如下

效果图

需要用到的画笔, 整体灰色的背景,  滑块, 滑动之后绿色背景, 字体

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); 

在onDraw中绘制  mMovex为手指滑动的X坐标

 @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.mipmap.arrow_right_small);
  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);

}

onTouch中进行滑动监听 负值

@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);
 }

整体代码

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.mipmap.arrow_right_small);
  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布局

<xxxx.LoadAwaySlideUnlockView
    android:id="@+id/slideUnlock"
    android:layout_marginLeft="3dp"
    android:layout_marginRight="3dp"
    android:layout_width="match_parent"
    android:layout_height="56dp"/>

activity中 添加提示文字和滑动监听即可

slideUnlock.setText("中间提示文字");
slideUnlock.setSlideListener(this);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • android 九宫格滑动解锁开机实例源码学习

    效果图由于网站占时不能上传,以后补上. NinePointLineView.java 复制代码 代码如下: package org.demo.custon_view; import org.demo.utils.MLog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; imp

  • Android唤醒、解锁屏幕代码实例

    解锁.唤醒屏幕用到KeyguardManager,KeyguardLock,PowerManager,PowerManager.WakeLock   所需权限: 复制代码 代码如下: <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /&

  • Android模拟实现滑动解锁界面

    本文实例为大家分享了Android模拟滑动解锁界面,供大家参考,具体内容如下 实现逻辑 自定义一个view继承view类,实现里面的方法 在构造方法中加载出图片资源.在onMeasure中获取背景的宽和高作为自定义控件的宽和高 在onDraw方法中绘制出滑块,在控件的布局文件中设置控件的背景图片 设置滑块的触摸事件,分别算出当手指按下屏幕.移动,离开屏幕时滑块的位置 在移动的过程中,对滑块的位置进行限定,使滑块的位置不能超过指定的区域 在手指离开屏幕的事件中判定手指的位置,如果滑块没有到达最右边

  • Android 自定义TextView实现滑动解锁高亮文字

    下面一段代码给大家分享Android 自定义TextView实现滑动解锁高亮文字效果,具体代码如下所示: public class HightLightTextView extends TextView { // 存储view的宽度 private int mTextViewWidth = 0; // 画笔 private Paint mPaint; // 线性渲染 private LinearGradient mLinearGradient; // 存储变换的matrix private Ma

  • Android点亮屏幕或屏幕解锁和锁定以及其他相关权限实现代码

    1.Android屏幕常亮/点亮 复制代码 代码如下: //保持屏幕常亮 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, LOCK_TAG); mWakeLock.acquire(); 复制代码 代码如下: //释

  • 使用Android自定义控件实现滑动解锁九宫格

    本文概述:  滑动解锁九宫格的分析: 1.需要自定义控件: 2.需要重写事件onTouchEvent(); 3.需要给九个点设置序号和坐标,这里用Map类就行: 4.需要判断是否到滑到过九点之一,并存储滑到过的点的序号,而且需要一个方法可以返回它们,这里用List类就行: 滑动解锁当前还是比较流行的,今天写了个简单的滑动解锁九宫格的例程,分享出来让初学者看看. 我的是这样的: Demo 首先,自定义一个View /** * 九宫格 */ public class NineGridView ext

  • Android编程实现禁止系统锁屏与解锁亮屏的方法

    本文实例讲述了Android编程实现禁止系统锁屏与解锁亮屏的方法.分享给大家供大家参考,具体如下: 需求: 某个时刻任务执行完毕,关闭屏幕,某时刻再开启屏幕继续执行任务 通常情况下,不设置屏幕常亮,系统会自动锁屏,锁屏后不能从代码解锁(疑问),所以我的做法是只让系统关闭屏幕,但不锁屏! WakeLock lock, unLock; KeyguardManager km; KeyguardLock kl; unLock = pm.newWakeLock(PowerManager.ACQUIRE_C

  • Android中判断屏幕是否亮屏和是否解锁功能

    1.屏幕是否亮屏: PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); //true为打开,false为关闭 boolean ifOpen = powerManager.isScreenOn(); 2.屏幕是否解锁: KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemServi

  • Android自定义滑动解锁控件使用详解

    最近的项目里用到了,在网上找不到合适的,于是自己写了个简单的,带回弹效果: 可以自定义的属性有: <!-- 滑动解锁控件 xml配置属性 --> <declare-styleable name="SlideToUnlockView"> <attr name="slideImageViewWidth" format="dimension"/><!-- 滑块宽度 --> <attr name=&q

  • android滑动解锁震动效果的开启和取消

    如果我们需要根据设置中的触摸震动开关来开启和取消滑动解锁的震动效果,就需要做以下修改了. 在LockScreen.java类中的LockScreen方法中的 复制代码 代码如下: else if (mUnlockWidget instanceof MultiWaveView) {            MultiWaveView multiWaveView = (MultiWaveView) mUnlockWidget; multiWaveView.setVibrateEnabled(Setti

随机推荐