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

Android实现九宫格解锁的方法

程序员文章站 2023-12-17 13:47:28
相信大家都有使用九宫格解锁,比如在设置手机安全项目中,可以使用九宫格解锁,提高安全性,以及在使用支付功能的时候,为了提高安全使用九宫锁,今天就为大家介绍android实现九...

相信大家都有使用九宫格解锁,比如在设置手机安全项目中,可以使用九宫格解锁,提高安全性,以及在使用支付功能的时候,为了提高安全使用九宫锁,今天就为大家介绍android实现九宫格的方法,分享给大家供大家参考。具体如下:
运行效果截图如下:

Android实现九宫格解锁的方法

具体代码如下:

布局文件如下:

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingbottom="@dimen/activity_vertical_margin"
  android:paddingleft="@dimen/activity_horizontal_margin"
  android:paddingright="@dimen/activity_horizontal_margin"
  android:paddingtop="@dimen/activity_vertical_margin"
  tools:context=".mainactivity" >

  <com.xuliugen.jiugongge.sudokuview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

</relativelayout>

从布局文件中可以看出需要自定义一个view用于绘制九宫格图案:
sudokuview.java

package com.xuliugen.jiugongge;

import android.content.context;
import android.graphics.canvas;
import android.graphics.color;
import android.graphics.paint;
import android.util.attributeset;
import android.view.motionevent;
import android.view.view;
import android.widget.toast;

public class sudokuview extends view {

  private static final int defalut_cell_width = 60; //默认的cell宽度
  private static final int defalut_cell_stroke_width = 2;
  private static final int defalut_space = defalut_cell_width >> 1;

  private cell mcells[] = new cell[9]; // 九宫格:定义用于存放九个数组

  private int mcellwidth;
  private int mcellradius;
  private int mcellstrokewidth;
  private int mspace;

  private paint mpaintnormal;
  private paint mpaintselected;
  private int mwidth;
  private int mheight;

  private float mcurrentx;
  private float mcurrenty;
  private boolean mfinish = false;

  private stringbuffer msbselected = new stringbuffer(20);

  /**
   * 下边是三个构造方法:每一个构造方法中有一个初始化操作
   */
  public sudokuview(context context) {
    super(context);
    init();
  }

  public sudokuview(context context, attributeset attrs) {
    super(context, attrs);
    init();
  }

  public sudokuview(context context, attributeset attrs, int defstyleattr) {
    super(context, attrs, defstyleattr);
    init();
  }

  /**
   * 初始化操作
   */
  private void init() {
    mcellwidth = densityutil.dip2px(getcontext(), defalut_cell_width);
    mcellradius = densityutil.dip2px(getcontext(), defalut_cell_width >> 1);
    mcellstrokewidth = densityutil.dip2px(getcontext(),
        defalut_cell_stroke_width);
    mspace = densityutil.dip2px(getcontext(), defalut_space);

    mpaintnormal = new paint();
    mpaintnormal.setcolor(color.white);
    mpaintnormal.setstrokewidth(mcellstrokewidth);
    mpaintnormal.setstyle(paint.style.stroke);
    mpaintnormal.setantialias(true);

    mpaintselected = new paint();
    mpaintselected.setcolor(color.cyan);
    mpaintselected.setstrokewidth(mcellstrokewidth);
    mpaintselected.setstyle(paint.style.stroke);
    mpaintselected.setantialias(true);

    cell cell;
    float x;
    float y;

    for (int i = 0; i < 9; i++) {
      x = mspace * (i % 3 + 1) + mcellradius + mcellwidth * (i % 3);
      y = mspace * (i / 3 + 1) + mcellradius + mcellwidth * (i / 3);

      cell = new cell(x, y);
      mcells[i] = cell;
    }
  }

  @override
  protected void ondraw(canvas canvas) {
    super.ondraw(canvas);
    drawcell(canvas);
    drawline(canvas);
  }

  private void drawcell(canvas canvas) {
    for (int i = 0; i < 9; i++) {
      canvas.drawcircle(mcells[i].getcenterx(), mcells[i].getcentery(),
          mcellradius, mcells[i].isselected() ? mpaintselected
              : mpaintnormal);
    }
  }

  private void drawline(canvas canvas) {
    if ("".equals(msbselected.tostring())) {
      return;
    }

    string[] selectedindexs = msbselected.tostring().split(",");
    cell cell = mcells[integer.valueof(selectedindexs[0])];
    cell nextcell;
    if (selectedindexs.length > 1) {
      for (int i = 1; i < selectedindexs.length; i++) {
        nextcell = mcells[integer.valueof(selectedindexs[i])];
        canvas.drawline(cell.getcenterx(), cell.getcentery(),
            nextcell.getcenterx(), nextcell.getcentery(),
            mpaintselected);

        cell = nextcell;
      }
    }

    if (!mfinish) {
      canvas.drawline(cell.getcenterx(), cell.getcentery(), mcurrentx,
          mcurrenty, mpaintselected);
    }
  }

  @override
  protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
    mwidth = getrealsize(widthmeasurespec);
    mheight = getrealsize(heightmeasurespec);

    setmeasureddimension(mwidth, mwidth);
  }

  private int getrealsize(int measurespc) {
    int result;
    int mode = measurespec.getmode(measurespc);
    int size = measurespec.getsize(measurespc);

    if (mode == measurespec.at_most || mode == measurespec.unspecified) {
      result = mcellwidth * 3 + mspace * 4;
    } else {
      result = size;
    }

    return result;
  }

  @override
  public boolean ontouchevent(motionevent event) {

    switch (event.getaction()) {
    case motionevent.action_down:
      if (mfinish) {
        for (int i = 0; i < 9; i++) {
          mcells[i].setselected(false);
        }
        mfinish = false;
        msbselected.delete(0, msbselected.length());
        invalidate();
        return false;
      }
      handledownevent(event);
      break;
    case motionevent.action_up:
      mfinish = true;
      toast.maketext(getcontext(), msbselected.tostring(),
          toast.length_short).show();
      break;
    case motionevent.action_move:
      handlemoveevent(event);
      break;
    }

    return true;
  }

  private void handlemoveevent(motionevent event) {
    int index = findcellindex(event.getx(), event.gety());
    if (index != -1) {
      mcells[index].setselected(true);
      msbselected.append(index).append(",");
    }
    invalidate();

    mcurrentx = event.getx();
    mcurrenty = event.gety();
  }

  private void handledownevent(motionevent event) {
    int index = findcellindex(event.getx(), event.gety());
    if (index != -1) {
      mcells[index].setselected(true);
      msbselected.append(index).append(",");
      invalidate();
    }

    mcurrentx = event.getx();
    mcurrenty = event.gety();
  }

  private int findcellindex(float x, float y) {
    float cellx;
    float celly;
    int result = -1;

    for (int i = 0; i < 9; i++) {
      if (mcells[i].isselected()) {
        continue;
      }

      cellx = mcells[i].getcenterx();
      celly = mcells[i].getcentery();

      float tempx = cellx - x;
      float tempy = celly - y;

      float distance = (float) math.sqrt(tempx * tempx + tempy * tempy);

      if (distance < mcellradius) {
        result = i;
        break;
      }
    }

    return result;
  }
}

mainactivity.java如下:

package com.xuliugen.jiugongge;

import android.os.bundle;
import android.support.v7.app.actionbaractivity;
import android.view.menu;
import android.view.menuitem;

public class mainactivity extends actionbaractivity {

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
  }

  @override
  public boolean oncreateoptionsmenu(menu menu) {
    getmenuinflater().inflate(r.menu.menu_main, menu);
    return true;
  }

  @override
  public boolean onoptionsitemselected(menuitem item) {
    int id = item.getitemid();

    if (id == r.id.action_settings) {
      return true;
    }
    return super.onoptionsitemselected(item);
  }
}


另外还需要一个存放圆圈的javabean

package com.xuliugen.jiugongge;

/**
 * 代表每一个九宫格圆圈的javabean
 * @author xuliugenpc
 */
public class cell {
  private float centerx;
  private float centery;
  private boolean selected;

  public cell(float x, float y) {
    centerx = x;
    centery = y;
  }

  public float getcenterx() {
    return centerx;
  }

  public void setcenterx(float centerx) {
    this.centerx = centerx;
  }

  public float getcentery() {
    return centery;
  }

  public void setcentery(float centery) {
    this.centery = centery;
  }

  public boolean isselected() {
    return selected;
  }

  public void setselected(boolean selected) {
    this.selected = selected;
  }
}

像素转换的工具类:

package com.xuliugen.jiugongge;

import android.content.context;
/**
 * 手机屏幕px转dp和dp转px工具类 
 * @author xuliugenpc
 */
public class densityutil {

  private static float scale;

  /**
   * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
   */
  public static int dip2px(context context, float dpvalue) {
    if (scale == 0) {
      scale = context.getresources().getdisplaymetrics().density;
    }
    return (int) (dpvalue * scale + 0.5f);
  }

  /**
   * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
   */
  public static int px2dip(context context, float pxvalue) {
    if (scale == 0) {
      scale = context.getresources().getdisplaymetrics().density;
    }
    return (int) (pxvalue / scale + 0.5f);
  }
}

以上就是android实现九宫格解锁的方法,希望本文所述对大家学习有所帮助。

上一篇:

下一篇: