通過android自定義View實現(xiàn)橫向的滑動解鎖,1另凌、滑動到中間會自動返回到原始的位置谱轨,2、滑動到底部會自動解鎖吠谢,會觸發(fā)解鎖的回調(diào)土童;首先看效果圖如下:
![](https://github.com/bitxiaozhang/SearchAndroid/blob/master/Search/images/ScreenGif.gif?raw=true)
實現(xiàn)以上部分一共分為三部分:
- 其中背景通過shape.xml實現(xiàn)
- 滑動的鎖是一張圖片
- 文字通過Paint繪制在中間,高度可定制
主要介紹一下實現(xiàn)的主要部分:
(1)有自定義的屬性如下:
<declare-styleable name="SlideLockView">
<attr name="lock_drawable" format="reference"/>
<attr name="lock_radius" format="dimension|reference"/>
<attr name="lock_tips_tx" format="string|reference"/>
<attr name="locl_tips_tx_size" format="dimension|reference"/>
<attr name="lock_tips_tx_color" format="color|reference"/>
</declare-styleable>
(2)重寫ondraw()方法,繪制文字和鎖:
@Overrideprotected void onDraw(Canvas canvas)
{
canvas.getClipBounds(mTipsTextRect);
int cHeight = mTipsTextRect.height();
int cWidth = mTipsTextRect.width();
mPaint.setTextAlign(Paint.Align.LEFT);
mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTipsTextRect);
float x = cWidth / 2f - mTipsTextRect.width() / 2f - mTipsTextRect.left;
float y = cHeight / 2f + mTipsTextRect.height() / 2f - mTipsTextRect.bottom;
canvas.drawText(mTipText, x, y, mPaint);
int rightMax = getWidth() - mLockRadius * 2;
if (mLocationX < 0) {
canvas.drawBitmap(mLockBitmap, 0, 0, mPaint);
} else if (mLocationX > rightMax) {
canvas.drawBitmap(mLockBitmap, rightMax, 0, mPaint);
} else {
canvas.drawBitmap(mLockBitmap, mLocationX, 0, mPaint);
}
}
(3)最重要的一步是觸摸事件的處理,1工坊、當觸摸屏幕是觸發(fā)ACTION_DOWN事件献汗,計算時候觸摸到鎖,只有當觸到鎖的時候才能滑動王污;2罢吃、手指移動時,獲得新的位置后計算新的位置昭齐,然后重新繪制尿招,若移動到另一端表示解鎖成功,執(zhí)行回調(diào)方法解鎖成功阱驾;3就谜、手指離開屏幕后重新reset View,動畫回到初始位置:
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
float xPos = event.getX();
float yPos = event.getY();
if (isTouchLock(xPos, yPos)) {
mLocationX = xPos - mLockRadius;
mIsDragable = true;
invalidate();
} else {
mIsDragable = false;
}
return true;
}
case MotionEvent.ACTION_MOVE: {
if (!mIsDragable) return true;
int rightMax = getWidth() - mLockRadius * 2;
resetLocationX(event.getX(),rightMax);
invalidate();
if (mLocationX >= rightMax){
mIsDragable = false;
mLocationX = 0;
invalidate();
if (mLockListener != null){
mLockListener.onOpenLockSuccess();
}
Log.e("AnimaterListener","解鎖成功");
}
return true;
}
case MotionEvent.ACTION_UP: {
if (!mIsDragable) return true;
resetLock();
break;
}
}
return super.onTouchEvent(event);
}
(4)重新回到初始位置resetLock代碼如下:
private void resetLock(){
ValueAnimator anim = ValueAnimator.ofFloat(mLocationX,0);
anim.setDuration(300);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
mLocationX = (Float) valueAnimator.getAnimatedValue();
invalidate();
}
});
anim.start();
}
這就是完成滑動解鎖的主要步驟,最后github地址在SlideView