個人原創(chuàng)文章晤愧,請尊重原創(chuàng)蛉腌,轉(zhuǎn)載請注明出處:吳磊的簡書:http://www.reibang.com/p/a4c29ec5712f
前言
- 最近自己寫的小項目中需要用到手勢解鎖,但是使用了多個開源的輪子效果都不理想烙丛,
想要京東金融的那種樣式,于是河咽,誰讓我是程序員呢?沒有什么就創(chuàng)造什么飒房。 - 手勢解鎖其實是一個比較輕量級的東西媚值,并不需要很多附加的狠毯、酷炫的功能褥芒,所以自定義一個
適合自己項目的是最好不過了。 - 本文出自安卓新手献酗,旨在引導(dǎo)初入安卓坑的同學(xué)們做出一個簡單的自定義View,大佬可以直接跳過凌摄,
另,有不足之處望讀者指出锨亏。
思路
其實實現(xiàn)這個自定義的控件有很多思路忙干,首先想到的是,要在View中創(chuàng)建9個圓捐迫,那么繼承GridLayout再合適不過了,但是經(jīng)過嘗試反浓,放棄了赞哗,邏輯變的更加復(fù)雜了,所以我選擇直接繼承View肪笋,那么下面就是需要處理的邏輯:
1 . 根據(jù)控件的大小,繪制9個圓圈藤乙;
2 . 在手指按到圓圈時,開始繪制路線而姐,并且將按下的圓圈置為選中狀態(tài)划咐;
3 . 在手指滑動時拴念,繪制一根跟隨手指移動的尖殃、起點為按下的圓圈的線;
4 .當(dāng)手指滑動到另外一個圓圈時缔俄,將第一個按下的圓圈與當(dāng)前圓圈用線連起來,并且繪制一根以當(dāng)前圓圈為起點的跟隨手指移動的線俐载;
5 .手指按下到圓圈時,以及每次劃過圓圈時遏佣,將此圓圈對應(yīng)的數(shù)字添加到數(shù)組;
6 .當(dāng)手指抬起時意敛,根據(jù)添加的數(shù)字判斷密碼是否正確膛虫,若錯誤草姻,則將所有的線稍刀、選中的圓,都置為錯誤的狀態(tài)综膀、顏色;
實現(xiàn)
-
首先看一下效果圖:
- Demo中實現(xiàn)的功能是:第一次為設(shè)置手勢密碼剧劝,第二次驗證手勢密碼是否與第一次相同项炼,運用的場景為設(shè)置手勢密碼和解鎖;
- 廢話不說锭部,下面上代碼,由于沒有添加xml中自定義屬性的功能取胎,所以所有代碼就一個UnlockView類湃窍,各類自定義的屬性通過set方法來設(shè)置闻蛀,另外需要一個Circle的內(nèi)部類您市,作為圓圈的對象,包含圓圈的XY坐標(biāo)以及狀態(tài)(選中薪棒、未選中、出錯)俐芯;
- 首先是OnMeasure方法,由于OnMeasure會在最開始被調(diào)用吧史,所以在這里獲取控件的寬高再合適不過:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = getMeasuredWidth();
height = getMeasuredHeight();
}
- 然后是OnLayout方法,在此方法中吨述,繪制9個圓圈莽使,以及初始化一些畫筆、顏色等參數(shù)芳肌,注意肋层,此方法可能會多次調(diào)用,所以要考慮到多次調(diào)用的情況栋猖,如初始化9個圓圈。:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//init all path/paint
mPath = new Path();
tempPath = new Path();
pathPaint = new Paint();
pathPaint.setColor(selectColor);
pathPaint.setDither(true);
pathPaint.setAntiAlias(true);
pathPaint.setStyle(Paint.Style.STROKE);
pathPaint.setStrokeCap(Paint.Cap.ROUND);
pathPaint.setStrokeJoin(Paint.Join.ROUND);
pathPaint.setStrokeWidth(pathWidth);
//普通狀態(tài)小圓畫筆
circletBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(circletBmp);
cirNorPaint = new Paint();
cirNorPaint.setAntiAlias(true);
cirNorPaint.setDither(true);
cirNorPaint.setColor(normalColor);
//選中狀態(tài)大圓畫筆
cirSelPaint = new Paint();
cirSelPaint.setAntiAlias(true);
cirSelPaint.setDither(true);
cirSelPaint.setStyle(Paint.Style.STROKE);
cirSelPaint.setStrokeWidth(strokeWidth);
cirSelPaint.setColor(selectColor);
//選中狀態(tài)小圓畫筆
smallCirSelPaint = new Paint();
smallCirSelPaint.setAntiAlias(true);
smallCirSelPaint.setDither(true);
smallCirSelPaint.setColor(selectColor);
//出錯狀態(tài)大圓畫筆
cirErrPaint = new Paint();
cirErrPaint.setAntiAlias(true);
cirErrPaint.setDither(true);
cirErrPaint.setStyle(Paint.Style.STROKE);
cirErrPaint.setStrokeWidth(strokeWidth);
cirErrPaint.setColor(errorColor);
//出錯狀態(tài)小圓畫筆
smallcirErrPaint = new Paint();
smallcirErrPaint.setAntiAlias(true);
smallcirErrPaint.setDither(true);
smallcirErrPaint.setColor(errorColor);
//init all circles
int hor = width / 6;
int ver = height / 6;
if(!hasNewCircles){
for (int i = 0; i < 9; i++) {
int tempX = (i % 3 + 1) * 2 * hor - hor;
int tempY = (i / 3 + 1) * 2 * ver - ver;
Circle circle = new Circle(i, tempX, tempY, CIRCLE_NORMAL);
circleList.add(circle);
}
}
hasNewCircles=true;
}
- 再然后是重中之中肃拜,OnTouchEvent方法雌团,在此方法中,需要監(jiān)聽手指的操作猛蔽,當(dāng)手指按到屏幕中的某個圓圈時,開始整個流程曼库,所以我們需要通過以下代碼判斷手指的落點是都在某個圓內(nèi):
@Nullable
private Circle getOuterCircle(int x, int y) {
for (int i = 0; i < circleList.size(); i++) {
Circle circle = circleList.get(i);
if ((x - circle.getX()) * (x - circle.getX()) + (y - circle.getY()) * (y - circle.getY()) <= normalR * normalR) {
if (circle.getState() != CIRCLE_SELECTED) {
return circle;
}
}
}
return null;
}
在ACTION_DOWN中略板,若落點在圓內(nèi),則將此圓的狀態(tài)置為選中狀態(tài)叮称,并且將可移動的連線的起點置為此圓的坐標(biāo)藐鹤;在ACTION_MOVE中蒂誉,若手指滑動,但未滑動到任何其他圓內(nèi)右锨,則只繪制一根移動的線,若手指在移動時移動到其他任何圓內(nèi)绍移,則將這個圓與一開始的圓用線連接,并且將可移動的線的起點置為此圓的坐標(biāo)轧抗,并將此圓對應(yīng)的序號添加到List中瞬测,最后將所有選中的圓的狀態(tài)置為選中并且重新繪制畫布;在ACTION_UP中月趟,需要判斷所有經(jīng)過的圓的序號跟預(yù)設(shè)密碼是否一致,并且重置所有狀態(tài)孝宗。每次操作后,都需要通過invalidate()通知重新onDraw下面上代碼:
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isShowError)
return true;
int curX = (int) event.getX();
int curY = (int) event.getY();
Circle circle = getOuterCircle(curX, curY);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
this.resetAll();
if (circle != null) {
rootX = circle.getX();
rootY = circle.getY();
circle.setState(CIRCLE_SELECTED);
pathCircleList.add(circle);
tempPath.moveTo(rootX, rootY);
addItem(circle.getPosition() + 1);
isUnlocking = true;
}
break;
case MotionEvent.ACTION_MOVE:
if (isUnlocking) {
mPath.reset();
mPath.addPath(tempPath);
mPath.moveTo(rootX, rootY);
mPath.lineTo(curX, curY);
handleMove(circle);
}
break;
case MotionEvent.ACTION_UP:
isUnlocking = false;
if (pathCircleList.size() > 0) {
mPath.reset();
mPath.addPath(tempPath);
StringBuilder sb = new StringBuilder();
for (Integer num : passList) {
sb.append(num);
}
if (this.mode == CREATE_MODE) {
if(createListener!=null){
createListener.onGestureCreated(sb.toString());
}else{
Log.e("UnLockView","Please set CreateGestureListener first!");
}
} else if(this.mode == CHECK_MODE){
if(listener!=null){
if (listener.isUnlockSuccess(sb.toString())) {
listener.onSuccess();
} else {
listener.onFailure();
for (Circle circle1 : pathCircleList) {
circle1.setState(CIRCLE_ERROR);
}
pathPaint.setColor(errorColor);
}
}else{
Log.e("UnLockView","Please set OnUnlockListener first!");
}
}else{
try {
throw new Exception("Please set mode first!");
} catch (Exception e) {
e.printStackTrace();
}
}
isShowError = true;
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(0);
}
}, 1000);
}
break;
}
invalidate();
return true;
}
- 最后是所有操作的提現(xiàn):onDraw(),在此方法中婚被,需要根據(jù)當(dāng)前9個圓的狀態(tài)繪制不同狀態(tài)的圓,并且要根據(jù)記錄的Path來繪制連線去枷,代碼如下:
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(circletBmp, 0, 0, null);
for (int i = 0; i < circleList.size(); i++) {
drawCircles(circleList.get(i));
}
canvas.drawPath(mPath, pathPaint);
}
/**
* called in onDraw for drawing all circles
*
* @param circle
*/
private void drawCircles(Circle circle) {
switch (circle.getState()) {
case CIRCLE_NORMAL:
mCanvas.drawCircle(circle.getX(), circle.getY(), normalR, cirNorPaint);
break;
case CIRCLE_SELECTED:
mCanvas.drawCircle(circle.getX(), circle.getY(), selectR, cirSelPaint);
mCanvas.drawCircle(circle.getX(), circle.getY(), normalR, smallCirSelPaint);
break;
case CIRCLE_ERROR:
mCanvas.drawCircle(circle.getX(), circle.getY(), selectR, cirErrPaint);
mCanvas.drawCircle(circle.getX(), circle.getY(), normalR, smallcirErrPaint);
break;
}
}
- 至此是复,所有的繪制、記錄的邏輯基本完成淑廊,最后就是添加監(jiān)聽。由于此控件需要同時用于創(chuàng)建手勢季惩、驗證手勢腻格,所以需要根據(jù)模式啥繁,添加不同的監(jiān)聽,首先添加的是創(chuàng)建手勢的監(jiān)聽旗闽,在ACTION_UP的時候,會將記錄的密碼回調(diào)給接口:
interface CreateGestureListener {
void onGestureCreated(String result);
}
public void setGestureListener(CreateGestureListener listener) {
this.createListener = listener;
}
然后是添加驗證手勢的接口:
interface OnUnlockListener {
boolean isUnlockSuccess(String result);
void onSuccess();
void onFailure();
}
public void setOnUnlockListener(OnUnlockListener listener) {
this.listener = listener;
}
好啦嫡意,到這里自定義手勢控制的View的邏輯基本完成捣辆,下面是將此控件用到布局后蔬螟,在Activity中操作的一個示例:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUnlockView= (UnlockView) findViewById(R.id.unlock);
mUnlockView.setMode(UnlockView.CREATE_MODE);
mUnlockView.setGestureListener(new UnlockView.CreateGestureListener() {
@Override
public void onGestureCreated(String result) {
pwd=result;
Toast.makeText(MainActivity.this,"Set Gesture Succeeded!",Toast.LENGTH_SHORT).show();
mUnlockView.setMode(UnlockView.CHECK_MODE);
}
});
mUnlockView.setOnUnlockListener(new UnlockView.OnUnlockListener() {
@Override
public boolean isUnlockSuccess(String result) {
if(result.equals(pwd)){
return true;
}else{
return false;
}
}
@Override
public void onSuccess() {
Toast.makeText(MainActivity.this,"Check Succeeded!",Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure() {
Toast.makeText(MainActivity.this,"Check Failed!",Toast.LENGTH_SHORT).show();
}
});
}
到這里就完成了整個自定義View的編寫旧巾、使用忍些。完整代碼及Demo可以在我的Github中查看菠齿。如發(fā)現(xiàn)有改進之處坐昙,望指正芋忿,萬分感謝!
個人原創(chuàng)文章戈钢,請尊重原創(chuàng),轉(zhuǎn)載請注明出處:吳磊的簡書:http://www.reibang.com/p/a4c29ec5712f
歡迎聯(lián)系我殉了、提供工作機會:
Github:https://github.com/MondeoWu/GestureUnlock
E-mail:331948214@qq.com
QQ:331948214