Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android招財進寶手勢密碼的實現

Android招財進寶手勢密碼的實現

編輯:關於Android編程

這幾個月都是在做招財進寶項目,一個高收益低風險的理財APP,有興趣的可以下載玩玩,收益不錯哦!!!

招財進寶下載地址:http://8.shengpay.com/

前段時間因產品需求,做了一個手勢密碼,跟支付寶的手勢密碼類似,這裡跟大家分享交流一下我實現的方式吧。


這篇來分享一下繪制手勢密碼的實現(主要是設置手勢密碼、校驗手勢密碼):


一、大致界面介紹:

\ \

圖1 圖2


\ \

圖3 圖4<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+zbwxo7rK1srGw9zC67vm1sa958PmIKG+1vfSqsrHu+bWxsnPt721xDm49szhyr7NvLHqus05uPa5rCYjMjY2ODQ7w9zC6828seqhvzwvcD4KPHA+zbwyo7rJ6NbDytbKxsPcwusgob684Mz9ytbKxrXEyuTI66OsVG91Y2hFdmVudLXEysK8/rSmwO2jrLvxyKHK5MjrtcTK1srGw9zC66OszazKsc/Uyr7U2snPt721xMzhyr7H+NPyob88L3A+CjxwPs28M6O61Nm75tbG0ru0zqOswb20zsPcwuuyu9K71sLM4cq+vefD5iChvtXiwO/U2sq1z9a1xMqxuvKjrLTtzvPM4cq+zsTX1rzTwcuhsNfz09K7zravtcS2r7utobGjrLTtzvPCt7620dXJq7HqvMfOqrrsyauhvzwvcD4KPHA+zbw0o7rQo9HpytbKxsPcwuujrMrkyOu1xMPcwuu07c7zo6y4+NPouuzJq8K3vrYmIzQzO7TtzvPOxNfWzOHKvjxicj4KPC9wPgo8cD48YnI+CjwvcD4KPHA+PGJyPgo8L3A+CjxwPjxzdHJvbmc+tv6hosq1z9bLvMK3o7o8L3N0cm9uZz48L3A+CjxwPjEuINX9yc+3vbXEzOHKvsf40/KjrNPD0ru49sDgKExvY2tJbmRpY2F0b3IuamF2YSnAtMq1z9ajrNfUtqjS5XZpZXfAtLvm1sY5uPbM4cq+zbyx6qO7PC9wPgo8cD4yLiDK1srGw9zC67vm1sbH+NPyo6zTw9K7uPbA4ChHZXN0dXJlQ29udGVudFZpZXcuamF2YSnAtMq1z9ajrMv8vMyz0NfUVmlld0dyb3VwwO/D5iwgzO280zm49kltYWdlVmlld8C0se3Kvs28seosINTab25MYXlvdXSjqKOpt723qNbQyejWw8v8w8e1xM671sOjuzwvcD4KPHA+My4gytbKxsK3vra75tbGo6wg08PSu7j2wOAoR2VzdHVyZURyYXdsaW5lLmphdmEpwLTKtc/Wo6y4tNC0b25Ub3VjaEV2ZW50KCm3vbeoo6zU2tXiuPa3vbeowO/D5rzgzP1Ub3VjaEV2ZW50ysK8/jogQUNUSU9OX0RPV06hokFDVElPTl9NT1ZFoaJBQ1RJT05fVVDKwrz+o6zAtLvm1sbK1srGway907K7zay149auvOS1xMK3vrajuzwvcD4KPHA+NC4gObj2teO1xLbUz/OjrNPD0ru49sDgKEdlc3R1cmVQb2ludC5qYXZhKcC0yrXP1qOssaO05sv8tcTOu9bDoaLXtMysoaKxs76wzbzGrLXIz+C52NDFz6KjuzwvcD4KPHA+NS4gytbKxsPcwuu1xLvxyKGjrMXQts/K1ta4tbHHsLXEzrvWw6OsuPm+3bustq/Ct762vq25/bXEteOjrLC0y7PQ8rGjtOa75tbGtcS147XEy7PQ8ijV4sDvtcS148uz0PK008nPtb3PwrfWsfDKx6O6MSwyLDMsNCw1LDYsNyw4LDkpo6yyu8Tc09DW2Li0tcS146GjPC9wPgo8cD48YnI+CjwvcD4KPHA+PGJyPgo8L3A+CjxwPjxzdHJvbmc+yP2horT6wuvKtc/Wsr3W6KO6PC9zdHJvbmc+PC9wPgo8cD48L3A+CjxwPgoxLtKq08PSu7j2wODAtLHtyr7V4jm49rXj1tC1xLXa0ru49rXjoaPA78PmsaPB9NPQtbHHsLXjtcTJz8/C1/PT0rXEuPe49s671sO1yMr00NQ8L3A+CjxwPgoyLtfUtqjS5Udyb3VwVmlld6Os08PAtNewObj2teOjrDm49rXjtcTP1Mq+ysfNqLn9SW1hZ2VWaWV3oaO4tNC0b25MYXlvdXTV4rj2t723qKOsyMO147C00OjH88XFwdA8L3A+CjxwPgozLrao0uXSu7j2v8nS1Lutz9+1xFZpZXejrLi00LRvblRvdWNoRXZlbnS3vbeoo6zU2tXiuPa3vbeowO/D5r340NC7rdaxz9+1xLLZ1/c8L3A+CjxwPgo0LsXQts/Tw7unytbWuLWxx7C1xM671sOjrMihs/a1scewtcTOu9bDyKXT68THObj2tePW0LXEw7+49rXjtcTOu9bDvfjQ0LHIvc+jrMjnufvTw7unteO1xM671sPU2sSz0ru49rXj1q7E2qOsxMfDtLWxxMe49rXj1sO7u7GzvrDNvMasoaM8L3A+Cjxicj4KPHA+vt/M5cq1z9a0+sLryOfPwqO6PC9wPgo8cD48c3Ryb25nPjEuIExvY2tJbmRpY2F0b3IuamF2YSDNvLC4zOHKvsDgPC9zdHJvbmc+PC9wPgo8cD48L3A+CjxwcmUgY2xhc3M9"brush:java;">package com.snda.fund.widget; import com.snda.fund.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.os.PowerManager; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.View; /** * * 手勢密碼圖案提示 * @author wulianghuan * */ public class LockIndicator extends View { private int numRow = 3; // 行 private int numColum = 3; // 列 private int patternWidth = 40; private int patternHeight = 40; private int f = 5; private int g = 5; private int strokeWidth = 3; private Paint paint = null; private Drawable patternNoraml = null; private Drawable patternPressed = null; private String lockPassStr; // 手勢密碼 public LockIndicator(Context paramContext) { super(paramContext); } public LockIndicator(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet, 0); paint = new Paint(); paint.setAntiAlias(true); paint.setStrokeWidth(strokeWidth); paint.setStyle(Paint.Style.STROKE); patternNoraml = getResources().getDrawable(R.drawable.lock_pattern_node_normal); patternPressed = getResources().getDrawable(R.drawable.lock_pattern_node_pressed); if (patternPressed != null) { patternWidth = patternPressed.getIntrinsicWidth(); patternHeight = patternPressed.getIntrinsicHeight(); this.f = (patternWidth / 4); this.g = (patternHeight / 4); patternPressed.setBounds(0, 0, patternWidth, patternHeight); patternNoraml.setBounds(0, 0, patternWidth, patternHeight); } } @Override protected void onDraw(Canvas canvas) { if ((patternPressed == null) || (patternNoraml == null)) { return; } // 繪制3*3的圖標 for (int i = 0; i < numRow; i++) { for (int j = 0; j < numColum; j++) { paint.setColor(-16777216); int i1 = j * patternHeight + j * this.g; int i2 = i * patternWidth + i * this.f; canvas.save(); canvas.translate(i1, i2); String curNum = String.valueOf(numColum * i + (j + 1)); if (!TextUtils.isEmpty(lockPassStr)) { if (lockPassStr.indexOf(curNum) == -1) { // 未選中 patternNoraml.draw(canvas); } else { // 被選中 patternPressed.draw(canvas); } } else { // 重置狀態 patternNoraml.draw(canvas); } canvas.restore(); } } } @Override protected void onMeasure(int paramInt1, int paramInt2) { if (patternPressed != null) setMeasuredDimension(numColum * patternHeight + this.g * (-1 + numColum), numRow * patternWidth + this.f * (-1 + numRow)); } /** * 請求重新繪制 * @param paramString 手勢密碼字符序列 */ public void setPath(String paramString) { lockPassStr = paramString; invalidate(); } }

2. GestureContentView.java 手勢密碼容器類

它繼承ViewGroup,通過addView()方法添加子viewe,手勢密碼的9個輸入點(GesturePoint)、GestureDrawline手勢密碼路徑都放在這個容器當中,下面是它的具體實現方法:

package com.wujay.fund.widget;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.wujay.fund.R;
import com.wujay.fund.common.AppUtil;
import com.wujay.fund.entity.GesturePoint;
import com.wujay.fund.widget.GestureDrawline.GestureCallBack;

/**
 * 手勢密碼容器類
 *
 */
public class GestureContentView extends ViewGroup {

	private int baseNum = 6;

	private int[] screenDispaly;
	
	/**
	 * 每個點區域的寬度
	 */
	private int blockWidth;
	/**
	 * 聲明一個集合用來封裝坐標集合
	 */
	private List list;
	private Context context;
	private boolean isVerify;
	private GestureDrawline gestureDrawline;
	
	/**
	 * 包含9個ImageView的容器,初始化
	 * @param context
	 * @param isVerify 是否為校驗手勢密碼
	 * @param passWord 用戶傳入密碼
	 * @param callBack 手勢繪制完畢的回調
	 */
	public GestureContentView(Context context, boolean isVerify, String passWord, GestureCallBack callBack) {
		super(context);
		screenDispaly = AppUtil.getScreenDispaly(context);
		blockWidth = screenDispaly[0]/3;
		this.list = new ArrayList();
		this.context = context;
		this.isVerify = isVerify;
		// 添加9個圖標
		addChild();
		// 初始化一個可以畫線的view
		gestureDrawline = new GestureDrawline(context, list, isVerify, passWord, callBack);
	}
	
	private void addChild(){
		for (int i = 0; i < 9; i++) {
			ImageView image = new ImageView(context);
			image.setBackgroundResource(R.drawable.gesture_node_normal);
			this.addView(image);
			invalidate();
			// 第幾行
			int row = i / 3;
			// 第幾列
			int col = i % 3;
			// 定義點的每個屬性
			int leftX = col*blockWidth+blockWidth/baseNum;
			int topY = row*blockWidth+blockWidth/baseNum;
			int rightX = col*blockWidth+blockWidth-blockWidth/baseNum;
			int bottomY = row*blockWidth+blockWidth-blockWidth/baseNum;
			GesturePoint p = new GesturePoint(leftX, rightX, topY, bottomY, image,i+1);
			this.list.add(p);
		}
	}
	
	public void setParentView(ViewGroup parent){
		// 得到屏幕的寬度
		int width = screenDispaly[0];
		LayoutParams layoutParams = new LayoutParams(width, width);
		this.setLayoutParams(layoutParams);
		gestureDrawline.setLayoutParams(layoutParams);
		parent.addView(gestureDrawline);
		parent.addView(this);
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		for (int i = 0; i < getChildCount(); i++) {
			//第幾行
			int row = i/3;
			//第幾列
			int col = i%3;
			View v = getChildAt(i);
			v.layout(col*blockWidth+blockWidth/baseNum, row*blockWidth+blockWidth/baseNum, 
					col*blockWidth+blockWidth-blockWidth/baseNum, row*blockWidth+blockWidth-blockWidth/baseNum);
		}
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		// 遍歷設置每個子view的大小
        for (int i = 0; i < getChildCount(); i++) {
            View v = getChildAt(i);
            v.measure(widthMeasureSpec, heightMeasureSpec);
        }
	}
	
	/**
	 * 保留路徑delayTime時間長
	 * @param delayTime
	 */
	public void clearDrawlineState(long delayTime) {
		gestureDrawline.clearDrawlineState(delayTime);
	}

}


3. GestureDrawline.java 手勢密碼路徑繪制類

根據OnTouchEvent方法的不同事件,ACTION_DOWN、ACTION_MOVE、ACTION_UP分別處理不同的邏輯。


package com.wujay.fund.widget;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.wujay.fund.common.AppUtil;
import com.wujay.fund.common.Constants;
import com.wujay.fund.entity.GesturePoint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff;
import android.os.Handler;
import android.util.Log;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

/**
 * 手勢密碼路徑繪制
 *
 */
public class GestureDrawline extends View {
	private int mov_x;// 聲明起點坐標
	private int mov_y;
	private Paint paint;// 聲明畫筆
	private Canvas canvas;// 畫布
	private Bitmap bitmap;// 位圖
	private List list;// 裝有各個view坐標的集合
	private List> lineList;// 記錄畫過的線
	private Map autoCheckPointMap;// 自動選中的情況點
	private boolean isDrawEnable = true; // 是否允許繪制
	
	/**
	 * 屏幕的寬度和高度
	 */
	private int[] screenDispaly;

	/**
	 * 手指當前在哪個Point內
	 */
	private GesturePoint currentPoint;
	/**
	 * 用戶繪圖的回調
	 */
	private GestureCallBack callBack;

	/**
	 * 用戶當前繪制的圖形密碼
	 */
	private StringBuilder passWordSb;
	
	/**
	 * 是否為校驗
	 */
	private boolean isVerify;
	
	/**
	 * 用戶傳入的passWord
	 */
	private String passWord;

	public GestureDrawline(Context context, List list, boolean isVerify,
			String passWord, GestureCallBack callBack) {
		super(context);
		screenDispaly = AppUtil.getScreenDispaly(context);
		paint = new Paint(Paint.DITHER_FLAG);// 創建一個畫筆
		bitmap = Bitmap.createBitmap(screenDispaly[0], screenDispaly[0], Bitmap.Config.ARGB_8888); // 設置位圖的寬高
		canvas = new Canvas();
		canvas.setBitmap(bitmap);
		paint.setStyle(Style.STROKE);// 設置非填充
		paint.setStrokeWidth(10);// 筆寬5像素
		paint.setColor(Color.rgb(245, 142, 33));// 設置默認連線顏色
		paint.setAntiAlias(true);// 不顯示鋸齒

		this.list = list;
		this.lineList = new ArrayList>();
		
		initAutoCheckPointMap();
		this.callBack = callBack;

		// 初始化密碼緩存
		this.isVerify = isVerify;
		this.passWordSb = new StringBuilder();
		this.passWord = passWord;
	}
	
	private void initAutoCheckPointMap() {
		autoCheckPointMap = new HashMap();
		autoCheckPointMap.put("1,3", getGesturePointByNum(2));
		autoCheckPointMap.put("1,7", getGesturePointByNum(4));
		autoCheckPointMap.put("1,9", getGesturePointByNum(5));
		autoCheckPointMap.put("2,8", getGesturePointByNum(5));
		autoCheckPointMap.put("3,7", getGesturePointByNum(5));
		autoCheckPointMap.put("3,9", getGesturePointByNum(6));
		autoCheckPointMap.put("4,6", getGesturePointByNum(5));
		autoCheckPointMap.put("7,9", getGesturePointByNum(8));
	}
	
	private GesturePoint getGesturePointByNum(int num) {
		for (GesturePoint point : list) {
			if (point.getNum() == num) {
				return point;
			}
		}
		return null;
	}

	// 畫位圖
	@Override
	protected void onDraw(Canvas canvas) {
		// super.onDraw(canvas);
		canvas.drawBitmap(bitmap, 0, 0, null);
	}

	// 觸摸事件
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (isDrawEnable == false) {
			// 當期不允許繪制
			return true;
		}
		paint.setColor(Color.rgb(245, 142, 33));// 設置默認連線顏色
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mov_x = (int) event.getX();
			mov_y = (int) event.getY();
			// 判斷當前點擊的位置是處於哪個點之內
			currentPoint = getPointAt(mov_x, mov_y);
			if (currentPoint != null) {
				currentPoint.setPointState(Constants.POINT_STATE_SELECTED);
				passWordSb.append(currentPoint.getNum());
			}
			// canvas.drawPoint(mov_x, mov_y, paint);// 畫點
			invalidate();
			break;
		case MotionEvent.ACTION_MOVE:
			clearScreenAndDrawList();

			// 得到當前移動位置是處於哪個點內
			GesturePoint pointAt = getPointAt((int) event.getX(), (int) event.getY());
			// 代表當前用戶手指處於點與點之前
			if (currentPoint == null && pointAt == null) {
				return true;
			} else {// 代表用戶的手指移動到了點上
				if (currentPoint == null) {// 先判斷當前的point是不是為null
					// 如果為空,那麼把手指移動到的點賦值給currentPoint
					currentPoint = pointAt;
					// 把currentPoint這個點設置選中為true;
					currentPoint.setPointState(Constants.POINT_STATE_SELECTED);
					passWordSb.append(currentPoint.getNum());
				}
			}
			if (pointAt == null || currentPoint.equals(pointAt) || Constants.POINT_STATE_SELECTED == pointAt.getPointState()) {
				// 點擊移動區域不在圓的區域,或者當前點擊的點與當前移動到的點的位置相同,或者當前點擊的點處於選中狀態
				// 那麼以當前的點中心為起點,以手指移動位置為終點畫線
				canvas.drawLine(currentPoint.getCenterX(), currentPoint.getCenterY(), event.getX(), event.getY(), paint);// 畫線
			} else {
				// 如果當前點擊的點與當前移動到的點的位置不同
				// 那麼以前前點的中心為起點,以手移動到的點的位置畫線
				canvas.drawLine(currentPoint.getCenterX(), currentPoint.getCenterY(), pointAt.getCenterX(), pointAt.getCenterY(), paint);// 畫線
				pointAt.setPointState(Constants.POINT_STATE_SELECTED);
				
				// 判斷是否中間點需要選中
				GesturePoint betweenPoint = getBetweenCheckPoint(currentPoint, pointAt);
				if (betweenPoint != null && Constants.POINT_STATE_SELECTED != betweenPoint.getPointState()) {
					// 存在中間點並且沒有被選中
					Pair pair1 = new Pair(currentPoint, betweenPoint);
					lineList.add(pair1);
					passWordSb.append(betweenPoint.getNum());
					Pair pair2 = new Pair(betweenPoint, pointAt);
					lineList.add(pair2);
					passWordSb.append(pointAt.getNum());
					// 設置中間點選中
					betweenPoint.setPointState(Constants.POINT_STATE_SELECTED);
					// 賦值當前的point;
					currentPoint = pointAt;
				} else {
					Pair pair = new Pair(currentPoint, pointAt);
					lineList.add(pair);
					passWordSb.append(pointAt.getNum());
					// 賦值當前的point;
					currentPoint = pointAt;
				}
			}
			invalidate();
			break;
		case MotionEvent.ACTION_UP:// 當手指抬起的時候
			if (isVerify) {
				// 手勢密碼校驗
				// 清掉屏幕上所有的線,只畫上集合裡面保存的線
				if (passWord.equals(passWordSb.toString())) {
					// 代表用戶繪制的密碼手勢與傳入的密碼相同
					callBack.checkedSuccess();
				} else {
					// 用戶繪制的密碼與傳入的密碼不同。
					callBack.checkedFail();
				}
			} else {
				callBack.onGestureCodeInput(passWordSb.toString());
			}
			break;
		default:
			break;
		}
		return true;
	}
	
	/**
	 * 指定時間去清除繪制的狀態
	 * @param delayTime 延遲執行時間
	 */
	public void clearDrawlineState(long delayTime) {
		if (delayTime > 0) {
			// 繪制紅色提示路線
			isDrawEnable = false;
			drawErrorPathTip();
		}
		new Handler().postDelayed(new clearStateRunnable(), delayTime);
	}
	
	/**
	 * 清除繪制狀態的線程
	 */
	final class clearStateRunnable implements Runnable {
		public void run() {
			// 重置passWordSb
			passWordSb = new StringBuilder();
			// 清空保存點的集合
			lineList.clear();
			// 重新繪制界面
			clearScreenAndDrawList();
			for (GesturePoint p : list) {
				p.setPointState(Constants.POINT_STATE_NORMAL);
			}
			invalidate();
			isDrawEnable = true;
		}
	}

	/**
	 * 通過點的位置去集合裡面查找這個點是包含在哪個Point裡面的
	 * 
	 * @param x
	 * @param y
	 * @return 如果沒有找到,則返回null,代表用戶當前移動的地方屬於點與點之間
	 */
	private GesturePoint getPointAt(int x, int y) {

		for (GesturePoint point : list) {
			// 先判斷x
			int leftX = point.getLeftX();
			int rightX = point.getRightX();
			if (!(x >= leftX && x < rightX)) {
				// 如果為假,則跳到下一個對比
				continue;
			}

			int topY = point.getTopY();
			int bottomY = point.getBottomY();
			if (!(y >= topY && y < bottomY)) {
				// 如果為假,則跳到下一個對比
				continue;
			}

			// 如果執行到這,那麼說明當前點擊的點的位置在遍歷到點的位置這個地方
			return point;
		}

		return null;
	}
	
	private GesturePoint getBetweenCheckPoint(GesturePoint pointStart, GesturePoint pointEnd) {
		int startNum = pointStart.getNum();
		int endNum = pointEnd.getNum();
		String key = null;
		if (startNum < endNum) {
			key = startNum + "," + endNum;
		} else {
			key = endNum + "," + startNum;
		}
		return autoCheckPointMap.get(key);
	}

	/**
	 * 清掉屏幕上所有的線,然後畫出集合裡面的線
	 */
	private void clearScreenAndDrawList() {
		canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
		for (Pair pair : lineList) {
			canvas.drawLine(pair.first.getCenterX(), pair.first.getCenterY(),
					pair.second.getCenterX(), pair.second.getCenterY(), paint);// 畫線
		}
	}
	
	/**
	 * 校驗錯誤/兩次繪制不一致提示
	 */
	private void drawErrorPathTip() {
		canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
		paint.setColor(Color.rgb(154, 7, 21));// 設置默認線路顏色
		for (Pair pair : lineList) {
			pair.first.setPointState(Constants.POINT_STATE_WRONG);
			pair.second.setPointState(Constants.POINT_STATE_WRONG);
			canvas.drawLine(pair.first.getCenterX(), pair.first.getCenterY(),
					pair.second.getCenterX(), pair.second.getCenterY(), paint);// 畫線
		}
		invalidate();
	}


	public interface GestureCallBack {
		
		/**
		 * 用戶設置/輸入了手勢密碼
		 */
		public abstract void onGestureCodeInput(String inputCode);

		/**
		 * 代表用戶繪制的密碼與傳入的密碼相同
		 */
		public abstract void checkedSuccess();

		/**
		 * 代表用戶繪制的密碼與傳入的密碼不相同
		 */
		public abstract void checkedFail();
	}

}

4.GestureEditActivity.java 手勢密碼設置界面

手勢密碼設置


代碼如下:

package com.wujay.fund;

import com.wujay.fund.R;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.wujay.fund.common.Constants;
import com.wujay.fund.widget.GestureContentView;
import com.wujay.fund.widget.GestureDrawline.GestureCallBack;
import com.wujay.fund.widget.LockIndicator;

/**
 * 
 * 手勢密碼設置界面
 *
 */
public class GestureEditActivity extends Activity implements OnClickListener {
	/** 手機號碼*/
	public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";
	/** 意圖 */
	public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";
	/** 首次提示繪制手勢密碼,可以選擇跳過 */
	public static final String PARAM_IS_FIRST_ADVICE = "PARAM_IS_FIRST_ADVICE";
	private TextView mTextTitle;
	private TextView mTextCancel;
	private LockIndicator mLockIndicator;
	private TextView mTextTip;
	private FrameLayout mGestureContainer;
	private GestureContentView mGestureContentView;
	private TextView mTextReset;
	private String mParamSetUpcode = null;
	private String mParamPhoneNumber;
	private boolean mIsFirstInput = true;
	private String mFirstPassword = null;
	private String mConfirmPassword = null;
	private int mParamIntentCode;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gesture_edit);
		setUpViews();
		setUpListeners();
	}
	
	private void setUpViews() {
		mTextTitle = (TextView) findViewById(R.id.text_title);
		mTextCancel = (TextView) findViewById(R.id.text_cancel);
		mTextReset = (TextView) findViewById(R.id.text_reset);
		mTextReset.setClickable(false);
		mLockIndicator = (LockIndicator) findViewById(R.id.lock_indicator);
		mTextTip = (TextView) findViewById(R.id.text_tip);
		mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container);
		// 初始化一個顯示各個點的viewGroup
		mGestureContentView = new GestureContentView(this, false, "", new GestureCallBack() {
			@Override
			public void onGestureCodeInput(String inputCode) {
				if (!isInputPassValidate(inputCode)) {
					mTextTip.setText(Html.fromHtml("最少鏈接4個點, 請重新輸入"));
					mGestureContentView.clearDrawlineState(0L);
					return;
				}
				if (mIsFirstInput) {
					mFirstPassword = inputCode;
					updateCodeList(inputCode);
					mGestureContentView.clearDrawlineState(0L);
					mTextReset.setClickable(true);
					mTextReset.setText(getString(R.string.reset_gesture_code));
				} else {
					if (inputCode.equals(mFirstPassword)) {
							Toast.makeText(GestureEditActivity.this, "設置成功", Toast.LENGTH_SHORT).show();
						mGestureContentView.clearDrawlineState(0L);
						GestureEditActivity.this.finish();
					} else {
						mTextTip.setText(Html.fromHtml("與上一次繪制不一致,請重新繪制"));
						// 左右移動動畫
						Animation shakeAnimation = AnimationUtils.loadAnimation(GestureEditActivity.this, R.anim.shake);
						mTextTip.startAnimation(shakeAnimation);
						// 保持繪制的線,1.5秒後清除
						mGestureContentView.clearDrawlineState(1300L);
					}
				}
				mIsFirstInput = false;
			}

			@Override
			public void checkedSuccess() {
				
			}

			@Override
			public void checkedFail() {
				
			}
		});
		// 設置手勢解鎖顯示到哪個布局裡面
		mGestureContentView.setParentView(mGestureContainer);
		updateCodeList("");
	}
	
	private void setUpListeners() {
		mTextCancel.setOnClickListener(this);
		mTextReset.setOnClickListener(this);
	}
	
	private void updateCodeList(String inputCode) {
		// 更新選擇的圖案
		mLockIndicator.setPath(inputCode);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.text_cancel:
			this.finish();
			break;
		case R.id.text_reset:
			mIsFirstInput = true;
			updateCodeList("");
			mTextTip.setText(getString(R.string.set_gesture_pattern));
			break;
		default:
			break;
		}
	}
	
	private boolean isInputPassValidate(String inputPassword) {
		if (TextUtils.isEmpty(inputPassword) || inputPassword.length() < 4) {
			return false;
		}
		return true;
	}
	
}


5. GestureVerifyActivity.java 手勢密碼校驗界面


代碼如下:

package com.wujay.fund;

import com.wujay.fund.R;
import com.wujay.fund.widget.GestureContentView;
import com.wujay.fund.widget.GestureDrawline.GestureCallBack;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 手勢繪制/校驗界面
 *
 */
public class GestureVerifyActivity extends Activity implements android.view.View.OnClickListener {
	/** 手機號碼*/
	public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";
	/** 意圖 */
	public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";
	private RelativeLayout mTopLayout;
	private TextView mTextTitle;
	private TextView mTextCancel;
	private ImageView mImgUserLogo;
	private TextView mTextPhoneNumber;
	private TextView mTextTip;
	private FrameLayout mGestureContainer;
	private GestureContentView mGestureContentView;
	private TextView mTextForget;
	private TextView mTextOther;
	private String mParamPhoneNumber;
	private long mExitTime = 0;
	private int mParamIntentCode;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gesture_verify);
		ObtainExtraData();
		setUpViews();
		setUpListeners();
	}
	
	private void ObtainExtraData() {
		mParamPhoneNumber = getIntent().getStringExtra(PARAM_PHONE_NUMBER);
		mParamIntentCode = getIntent().getIntExtra(PARAM_INTENT_CODE, 0);
	}
	
	private void setUpViews() {
		mTopLayout = (RelativeLayout) findViewById(R.id.top_layout);
		mTextTitle = (TextView) findViewById(R.id.text_title);
		mTextCancel = (TextView) findViewById(R.id.text_cancel);
		mImgUserLogo = (ImageView) findViewById(R.id.user_logo);
		mTextPhoneNumber = (TextView) findViewById(R.id.text_phone_number);
		mTextTip = (TextView) findViewById(R.id.text_tip);
		mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container);
		mTextForget = (TextView) findViewById(R.id.text_forget_gesture);
		mTextOther = (TextView) findViewById(R.id.text_other_account);
		
		
		// 初始化一個顯示各個點的viewGroup
		mGestureContentView = new GestureContentView(this, true, "1235789",
				new GestureCallBack() {

					@Override
					public void onGestureCodeInput(String inputCode) {

					}

					@Override
					public void checkedSuccess() {
						mGestureContentView.clearDrawlineState(0L);
						Toast.makeText(GestureVerifyActivity.this, "密碼正確", 1000).show();
						GestureVerifyActivity.this.finish();
					}

					@Override
					public void checkedFail() {
						mGestureContentView.clearDrawlineState(1300L);
						mTextTip.setVisibility(View.VISIBLE);
						mTextTip.setText(Html
								.fromHtml("密碼錯誤"));
						// 左右移動動畫
						Animation shakeAnimation = AnimationUtils.loadAnimation(GestureVerifyActivity.this, R.anim.shake);
						mTextTip.startAnimation(shakeAnimation);
					}
				});
		// 設置手勢解鎖顯示到哪個布局裡面
		mGestureContentView.setParentView(mGestureContainer);
	}
	
	private void setUpListeners() {
		mTextCancel.setOnClickListener(this);
		mTextForget.setOnClickListener(this);
		mTextOther.setOnClickListener(this);
	}
	
	private String getProtectedMobile(String phoneNumber) {
		if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() < 11) {
			return "";
		}
		StringBuilder builder = new StringBuilder();
		builder.append(phoneNumber.subSequence(0,3));
		builder.append("****");
		builder.append(phoneNumber.subSequence(7,11));
		return builder.toString();
	}
	
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.text_cancel:
			this.finish();
			break;
		default:
			break;
		}
	}
	
}


以上是手勢密碼實現的關鍵代碼,我把項目中的模塊代碼整理出來,新建了一個project,供大家分享和交流

源碼下載地址:


源碼下載地址:http://download.csdn.net/detail/wulianghuan/8115995



  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved