欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android手势密码的实现

程序员文章站 2024-03-01 23:44:28
一、大致界面介绍: 图1 图2 图3 图4 图1:手势密码绘制界面 【主要是绘制上方的9个提示图标和9个宫格密码图标】 图2:设置手势密码 【监...

一、大致界面介绍:

Android手势密码的实现

图1

Android手势密码的实现

图2

Android手势密码的实现

图3

Android手势密码的实现

图4

图1:手势密码绘制界面 【主要是绘制上方的9个提示图标和9个宫格密码图标】

图2:设置手势密码 【监听手势的输入,touchevent的事件处理,获取输入的手势密码,同时显示在上方的提示区域】

图3:再绘制一次,两次密码不一致提示界面 【这里在实现的时候,错误提示文字加了“左右晃动的动画”,错误路径颜色标记为红色】

图4:校验手势密码,输入的密码错误,给予红色路径+错误文字提示

二、实现思路:

1. 正上方的提示区域,用一个类(lockindicator.java)来实现,自定义view来绘制9个提示图标;

2. 手势密码绘制区域,用一个类(gesturecontentview.java)来实现,它继承自viewgroup里面, 添加9个imageview来表示图标, 在onlayout()方法中设置它们的位置;

3. 手势路径绘制, 用一个类(gesturedrawline.java)来实现,复写ontouchevent()方法,在这个方法里面监听touchevent事件: action_down、action_move、action_up事件,来绘制手势连接不同点之间的路径;

4. 9个点的对象,用一个类(gesturepoint.java)来实现,保存它的位置、状态、背景图片等相关信息;

5. 手势密码的获取,判断手指当前的位置,根据滑动路径经过的点,按顺序保存绘制的点的顺序(这里的点顺序从上到下分别是:1,2,3,4,5,6,7,8,9),不能有重复的点。

三、代码实现步骤:

1.要用一个类来表示这9个点中的第一个点。里面保留有当前点的上下左右的各个位置等属性

2.自定义groupview,用来装9个点,9个点的显示是通过imageview。复写onlayout这个方法,让点按需求排列

3.定义一个可以画线的view,复写ontouchevent方法,在这个方法里面进行画直线的操作

4.判断用户手指当前的位置,取出当前的位置去与那9个点中的每个点的位置进行比较,如果用户点的位置在某一个点之内,那么当那个点置换背景图片。

具体实现代码如下:

1.lockindicator.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<gesturepoint> 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<gesturepoint>(); 
    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<gesturepoint> list;// 装有各个view坐标的集合 
  private list<pair<gesturepoint, gesturepoint>> linelist;// 记录画过的线 
  private map<string, gesturepoint> 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<gesturepoint> 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<pair<gesturepoint, gesturepoint>>(); 
    initautocheckpointmap(); 
    this.callback = callback; 
    // 初始化密码缓存 
    this.isverify = isverify; 
    this.passwordsb = new stringbuilder(); 
    this.password = password; 
  } 
  private void initautocheckpointmap() { 
    autocheckpointmap = new hashmap<string,gesturepoint>(); 
    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<gesturepoint, gesturepoint> pair1 = new pair<gesturepoint, gesturepoint>(currentpoint, betweenpoint); 
          linelist.add(pair1); 
          passwordsb.append(betweenpoint.getnum()); 
          pair<gesturepoint, gesturepoint> pair2 = new pair<gesturepoint, gesturepoint>(betweenpoint, pointat); 
          linelist.add(pair2); 
          passwordsb.append(pointat.getnum()); 
          // 设置中间点选中 
          betweenpoint.setpointstate(constants.point_state_selected); 
          // 赋值当前的point; 
          currentpoint = pointat; 
        } else { 
          pair<gesturepoint, gesturepoint> pair = new pair<gesturepoint, gesturepoint>(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<gesturepoint, gesturepoint> 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<gesturepoint, gesturepoint> 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("<font color='#c70c1e'>最少链接4个点, 请重新输入</font>")); 
          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("<font color='#c70c1e'>与上一次绘制不一致,请重新绘制</font>")); 
            // 左右移动动画 
            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("<font color='#c70c1e'>密码错误</font>")); 
            // 左右移动动画 
            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,供大家分享和交流。欲了解更多资讯请登录网站了解!