Android手势密码

首先感谢:http://blog.csdn.net/wulianghuan/article/details/40536635

我是在这个基础上进行的二次开发。效果图就是原创博主给出的,只是做了优化和修改。还是赘述一下实现思路吧:

 

  • 九宫格中的点作为一个实体类,它包含了它的一些属性,比如它的背景色(根据手势和是否画对显示不同的效果),代表的数字,位置信息(用于生成手势密码)。所谓手势密码也就是通过手走过的路径它所经过的点形成的一串数字密码(1~9)。
  • 九宫格的绘制,采用的是继承ViewGroup实现的。里面按照九宫格的方式排列3*3的点。更好地适配性,采用手机分辨率均分的方式(里面有个工具类用于获取屏幕的分辨率)。
  • 链接线的绘制,连接线分为密码成功与否两种显示不同的效果。它要依附于point并记录下连接顺序并生成数字密码。核心就在这里,它要放出一个接口返回结果。
  • 导航图,我们可以通过画九个圆实现,坐标就是九宫格画出路径保存的坐标。
  • 密码不能无限输入,采用了android的数据存储SharedPreferences记录密码。

下面我们来看具体栗子:

绘制密码UI:draw_psw_canvas_layout.xml

 



    

        

        
    

    

        

        
    

    
    
    
    



校验密码UI:draw_gesture_verify_layout.xml


    
    

        

        

        
    

    
    

    

        

        
    


密码结果显示UI:draw_gesture_result_layout.xml



    
	

密码错误动画:shake.xml记得放在res/anim文件夹下





主文件有:

1.绘制密码:GestureLockActivity

 

package com.lzy.gesture;

import com.lzy.gesture.utils.AppManager;
import com.lzy.gesture.weiget.GestureContentView;
import com.lzy.gesture.weiget.GestureDrawline.GestureCallBack;
import com.lzy.gesture.weiget.LockIndicator;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
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;

/**
 * 
 * 手势密码设置界面
 *
 */
public class GestureLockActivity extends Activity implements OnClickListener {
	private TextView mTextCancel;
	private LockIndicator mLockIndicator;
	private TextView mTextTip;
	private FrameLayout mGestureContainer;
	private GestureContentView mGestureContentView;
	private TextView mTextReset;
	private boolean mIsFirstInput = true;
	private String mFirstPassword = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.draw_psw_canvas_layout);
		AppManager.getAppManager().addActivity(this);
		
		SharedPreferences sharedPreferences = getSharedPreferences("gesturePsw", Context.MODE_PRIVATE);
		String gesturePsw = sharedPreferences.getString("gesturePsw", "");//new SharePreferHelper(this).getPsw();
		if (!"".equals(gesturePsw) || !TextUtils.isEmpty(gesturePsw)) {
			Intent intent = new Intent(GestureLockActivity.this, GestureVerifyActivity.class);
			intent.putExtra("gesturePsw", gesturePsw);
			intent.putExtra("phoneNumer", "15852188888");
			startActivity(intent);
		}
		setUpViews();
		setUpListeners();
	}
	
	private void setUpViews() {
		mTextCancel = (TextView) findViewById(R.id.text_cancel);
		mTextReset = (TextView) findViewById(R.id.text_show);
		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("重新设置手势密码");
				} else {
					if (inputCode.equals(mFirstPassword)) {
						Toast.makeText(GestureLockActivity.this, "设置成功", Toast.LENGTH_SHORT).show();
						
						SharedPreferences sp = getSharedPreferences("gesturePsw", Context.MODE_PRIVATE);
						sp.edit().putString("gesturePsw", inputCode).commit();
						
						mGestureContentView.clearDrawlineState(0L);
						Intent intent = new Intent(GestureLockActivity.this, ResultShowActivity.class);
						intent.putExtra("code", inputCode);
						startActivity(intent);
						GestureLockActivity.this.finish();
					} else {
						mTextTip.setText(Html.fromHtml("与上一次绘制不一致,请重新绘制"));
						// 左右移动动画
						Animation shakeAnimation = AnimationUtils.loadAnimation(GestureLockActivity.this, R.anim.shake);
						mTextTip.startAnimation(shakeAnimation);
						// 保持绘制的线,1.5秒后清除
						mGestureContentView.clearDrawlineState(1500L);
					}
				}
				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_show:
			mIsFirstInput = true;
			updateCodeList("");
			mTextTip.setText("绘制解锁图案");
			break;
		default:
			break;
		}
	}
	
	private boolean isInputPassValidate(String inputPassword) {
		if (TextUtils.isEmpty(inputPassword) || inputPassword.length() < 4) {
			return false;
		}
		return true;
	}
	
}


2.手势校验:GestureVerifyActivity

package com.lzy.gesture;

import com.lzy.gesture.utils.AppManager;
import com.lzy.gesture.weiget.GestureContentView;
import com.lzy.gesture.weiget.GestureDrawline.GestureCallBack;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
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.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 手势绘制/校验界面
 *
 */
public class GestureVerifyActivity extends Activity implements android.view.View.OnClickListener {
	private TextView mTextTip;
	private FrameLayout mGestureContainer;
	private GestureContentView mGestureContentView;
	private TextView mTextForget;
	private TextView mTextOther;
	private TextView phoneTextView;

	private int count = 3;//解锁操作三次
	
	private String gestureCode;
	private String phoneNumber;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.draw_gesture_verify_layout);
		AppManager.getAppManager().addActivity(this);
		
		ObtainExtraData();
		setUpViews();
		setUpListeners();
	}
	
	private void ObtainExtraData() {
		Intent intent = getIntent();
		gestureCode = intent.getStringExtra("gesturePsw");
		phoneNumber = intent.getStringExtra("phoneNumer");
	}
	
	private void setUpViews() {
		phoneTextView = (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);
		
		phoneTextView.setText(getProtectedMobile(phoneNumber));
		
		// 初始化一个显示各个点的viewGroup
		mGestureContentView = new GestureContentView(this, true, gestureCode,
				new GestureCallBack() {

					@Override
					public void onGestureCodeInput(String inputCode) {
						
					}

					@Override
					public void checkedSuccess() {
						if (count > 0) {
							mGestureContentView.clearDrawlineState(0L);
							
							Toast.makeText(GestureVerifyActivity.this, "密码正确", Toast.LENGTH_SHORT).show();
							
							Intent intent = new Intent(GestureVerifyActivity.this, ResultShowActivity.class);
							intent.putExtra("code", gestureCode);
							startActivity(intent);
							
							GestureVerifyActivity.this.finish();
							AppManager.getAppManager().finishAllActivity();
						}else {
							showExceedTimes();
						}
					}

					@Override
					public void checkedFail() {
						count --;
						if (count > -1) {
							mGestureContentView.clearDrawlineState(1300L);
							mTextTip.setVisibility(View.VISIBLE);
							mTextTip.setText(Html
									.fromHtml("密码错误,还有"
											+ "" + count + "" 
											+ "次机会"));
							// 左右移动动画
							Animation shakeAnimation = AnimationUtils.loadAnimation(GestureVerifyActivity.this, R.anim.shake);
							mTextTip.startAnimation(shakeAnimation);
						}else {
							showExceedTimes();
						}
					}
				});
		// 设置手势解锁显示到哪个布局里面
		mGestureContentView.setParentView(mGestureContainer);
	}
	
	private void setUpListeners() {
		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_forget_gesture:
			openResultActivity();
			AppManager.getAppManager().finishAllActivity();
			break;
		case R.id.text_other_account:
			Toast.makeText(getApplicationContext(), "其它方式登录", Toast.LENGTH_SHORT).show();
			AppManager.getAppManager().finishAllActivity();
			this.finish();
			break;
		default:
			break;
		}
	}
	
	private void showExceedTimes(){
		AlertDialog.Builder dialog = new Builder(GestureVerifyActivity.this);
		dialog.setTitle("提示")
			.setMessage("解锁超过三次!!!是否找回密码?")
			.setNegativeButton("取消", new OnClickListener() {
			
				@Override
				public void onClick(DialogInterface dialog, int which) {
					AppManager.getAppManager().finishAllActivity();
				}
			})
			.setPositiveButton("确定", new OnClickListener() {
			
				@Override
				public void onClick(DialogInterface dialog, int which) {
					openResultActivity();
				}
			})
			.show();
	}
	
	private void openResultActivity() {
		Intent intent = new Intent(GestureVerifyActivity.this, ResultShowActivity.class);
		intent.putExtra("code", gestureCode);
		startActivity(intent);
		this.finish();
	}
}


3.手势密码显示:ResultShowActivity

package com.lzy.gesture;

import com.lzy.gesture.utils.AppManager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ResultShowActivity extends Activity{
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.draw_gesture_result_layout);
		AppManager.getAppManager().addActivity(this);
		
		Intent intent = getIntent();
		TextView textView = (TextView) findViewById(R.id.result);
		textView.setText("手势密码是:" + intent.getStringExtra("code"));
	}
	
	@Override
	protected void onDestroy() {
		AppManager.getAppManager().finishAllActivity();
	}
}


核心自定义View

1.九宫格绘制:GestureContentView

package com.lzy.gesture.weiget;

import java.util.ArrayList;
import java.util.List;

import com.lzy.gesture.R;
import com.lzy.gesture.entity.GesturePoint;
import com.lzy.gesture.utils.Utils;
import com.lzy.gesture.weiget.GestureDrawline.GestureCallBack;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * 手势密码容器类
 *
 */
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 gestureCallBack 手势绘制完毕的回调
	 */
	public GestureContentView(Context context, boolean isVerify, String passWord, GestureCallBack gestureCallBack) {
		super(context);
		screenDispaly = Utils.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, gestureCallBack);
	}
	
	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);
	}

}


2.连接线的绘制:GestureDrawline

package com.lzy.gesture.weiget;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lzy.gesture.constant.PointState;
import com.lzy.gesture.entity.GesturePoint;
import com.lzy.gesture.utils.Utils;

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.Pair;
import android.view.MotionEvent;
import android.view.View;

/**
 * 手势密码路径绘制
 *
 */
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 = Utils.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(255, 255, 255));// 设置默认连线颜色
		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(255, 255, 255));// 设置默认连线颜色
		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(PointState.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(PointState.SELECTED);
					passWordSb.append(currentPoint.getNum());
				}
			}
			if (pointAt == null || currentPoint.equals(pointAt) || PointState.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(PointState.SELECTED);
				
				// 判断是否中间点需要选中
				GesturePoint betweenPoint = getBetweenCheckPoint(currentPoint, pointAt);
				if (betweenPoint != null && PointState.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(PointState.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(PointState.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(PointState.ERROR);
			pair.second.setPointState(PointState.ERROR);
			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();
	}

}


3.导航九宫图:LockIndicator

package com.lzy.gesture.weiget;

import com.lzy.gesture.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

/**
 * 
 * 手势密码图案提示
 *
 */
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();
	}
}


里面用到的其他文件:

1.密码保存:SharePreferHelper

package com.lzy.gesture.utils;

import android.content.Context;
import android.content.SharedPreferences;

public class SharePreferHelper {
	private String psw;
	private Context context;
	private SharedPreferences sharedPreferences;
	
	public SharePreferHelper(Context context) {
		this.context = context;
		this.sharedPreferences = context.getSharedPreferences("gesturePsw", Context.MODE_PRIVATE);
	}

	public String getPsw() {
		psw = sharedPreferences.getString("gesturePsw", "");
		return psw;
	}
}


2.获取手机分辨率:Utils

package com.lzy.gesture.utils;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.WindowManager;

/**
 * @author luzhenyu
 * @descrip 

* 工具类 *

* */ public class Utils { /** * 获取屏幕分辨率 * * @param context * @return [0] - width,[1] - height */ public static int[] getScreenDispaly(Context context) { WindowManager windowManager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics displayMetrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(displayMetrics); int width = displayMetrics.widthPixels; int height = displayMetrics.heightPixels; int [] result = {width, height}; return result; } }


3.点状态,以便改变背景色:PointState

package com.lzy.gesture.constant;

/**
 * @author luzhenyu
 * @descrip 

九宫格点的状态

* */ public class PointState { public static final int NORMAL = 0x00; public static final int SELECTED = 0x01; public static final int ERROR = 0x10; }


4.AppManager管理类

package com.lzy.gesture.utils;

import java.util.Stack;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

/**
 * @author luzhenyu
 * @descrip 

* 应用程序Activity管理类:用于Activity管理和应用程序退出 *

*/ public class AppManager { private static Stack activityStack; private static AppManager instance; private AppManager() { } /** * 单例模式 */ public static AppManager getAppManager() { if (instance == null) { instance = new AppManager(); } return instance; } /** * 添加Activity到堆栈 */ public void addActivity(Activity activity) { if (activityStack == null) { activityStack = new Stack(); } activityStack.add(activity); } /** * 获取当前Activity(堆栈中最后一个压入的) */ public Activity currentActivity() { Activity activity = activityStack.lastElement(); return activity; } /** * 结束当前Activity(堆栈中最后一个压入的) */ public void finishActivity() { Activity activity = activityStack.lastElement(); finishActivity(activity); } /** * 结束指定的Activity */ public void finishActivity(Activity activity) { if (activity != null) { activityStack.remove(activity); activity.finish(); activity = null; } } /** * 结束指定类名的Activity */ public void finishActivity(Class cls) { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { finishActivity(activity); } } } /** * 结束所有Activity */ public void finishAllActivity() { for (int i = 0, size = activityStack.size(); i < size; i++) { if (null != activityStack.get(i)) { activityStack.get(i).finish(); } } activityStack.clear(); } /** * 退出应用程序 */ public void AppExit(Context context) { try { finishAllActivity(); ActivityManager activityMgr = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); activityMgr.restartPackage(context.getPackageName()); System.exit(0); } catch (Exception e) { } } }


5.点实体类:GesturePoint

package com.lzy.gesture.entity;


import com.lzy.gesture.R;
import com.lzy.gesture.constant.PointState;
import android.widget.ImageView;

/**
 * @author luzhenyu
 * @descrip 

手势的点实体,用于记录点的属性(位置,代表的值,背景色)

* */ public class GesturePoint { /** * 左边x的值 */ private int leftX; /** * 右边x的值 */ private int rightX; /** * 上边y的值 */ private int topY; /** * 下边y的值 */ private int bottomY; /** * 这个点对应的ImageView控件 */ private ImageView image; /** * 中心x值 */ private int centerX; /** * 中心y值 */ private int centerY; /** * 状态值 */ private int pointState; /** * 代表这个Point对象代表的数字,从1开始(直接感觉从1开始) */ private int num; public GesturePoint(int leftX, int rightX, int topY, int bottomY, ImageView image, int num) { super(); this.leftX = leftX; this.rightX = rightX; this.topY = topY; this.bottomY = bottomY; this.image = image; this.centerX = (leftX + rightX) / 2; this.centerY = (topY + bottomY) / 2; this.num = num; } public int getLeftX() { return leftX; } public void setLeftX(int leftX) { this.leftX = leftX; } public int getRightX() { return rightX; } public void setRightX(int rightX) { this.rightX = rightX; } public int getTopY() { return topY; } public void setTopY(int topY) { this.topY = topY; } public int getBottomY() { return bottomY; } public void setBottomY(int bottomY) { this.bottomY = bottomY; } public ImageView getImage() { return image; } public void setImage(ImageView image) { this.image = image; } public int getCenterX() { return centerX; } public void setCenterX(int centerX) { this.centerX = centerX; } public int getCenterY() { return centerY; } public void setCenterY(int centerY) { this.centerY = centerY; } public int getPointState() { return pointState; } public void setPointState(int state) { pointState = state; switch (state) { case PointState.NORMAL: this.image.setBackgroundResource(R.drawable.gesture_node_normal); break; case PointState.SELECTED: this.image.setBackgroundResource(R.drawable.gesture_node_pressed); break; case PointState.ERROR: this.image.setBackgroundResource(R.drawable.gesture_node_wrong); break; default: break; } } public int getNum() { return num; } public void setNum(int num) { this.num = num; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + bottomY; result = prime * result + ((image == null) ? 0 : image.hashCode()); result = prime * result + leftX; result = prime * result + rightX; result = prime * result + topY; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GesturePoint other = (GesturePoint) obj; if (bottomY != other.bottomY) return false; if (image == null) { if (other.image != null) return false; } else if (!image.equals(other.image)) return false; if (leftX != other.leftX) return false; if (rightX != other.rightX) return false; if (topY != other.topY) return false; return true; } @Override public String toString() { return "Point [leftX=" + leftX + ", rightX=" + rightX + ", topY=" + topY + ", bottomY=" + bottomY + "]"; } }

 

源码下载:点我下载

【欢迎上码】

【微信公众号搜索 h2o2s2】

Android手势密码_第1张图片

你可能感兴趣的:(小小功能,android手势解码)