Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> 使用Android自定義控件實現滑動解鎖九宮格

使用Android自定義控件實現滑動解鎖九宮格

編輯:Android開發實例

本文概述:

 滑動解鎖九宮格的分析:

1、需要自定義控件;
2、需要重寫事件onTouchEvent();
3、需要給九個點設置序號和坐標,這裡用Map類就行;
4、需要判斷是否到滑到過九點之一,並存儲滑到過的點的序號,而且需要一個方法可以返回它們,這裡用List類就行;

滑動解鎖當前還是比較流行的,今天寫了個簡單的滑動解鎖九宮格的例程,分享出來讓初學者看看。

我的是這樣的:

Demo

首先,自定義一個View

/**
 * 九宮格
 */
public class NineGridView extends View {
  private int width;//該控件的寬
  private int height;//該控件的高
  private Paint mPaintBigCircle;//用於畫外圓
  private Paint mPaintSmallCircle;//用於畫內圓
  private Paint mPaintLine;//用於畫線
  private Paint mPaintText;//用於畫文本
  private Path path;//手勢劃線時需要用到它
  private Map<Integer, Float[]> pointContainer;//存儲九個點的坐標
  private List<Integer> pointerSlipped;//存儲得到的九宮格密碼
  public List<Integer> getPointerSlipped() {
    return pointerSlipped;
  }
  public void setPointerSlipped(List<Integer> pointerSlipped) {
    this.pointerSlipped = pointerSlipped;
  }
  public NineGridView(Context context) {
    super(context);
  }
  public NineGridView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mPaintBigCircle = new Paint();
    mPaintBigCircle.setColor(Color.BLUE);
    mPaintBigCircle.setStyle(Paint.Style.STROKE);//不充滿
    mPaintBigCircle.setAntiAlias(true);//抗鋸齒打開
    mPaintSmallCircle = new Paint();
    mPaintSmallCircle.setColor(Color.GREEN);
    mPaintSmallCircle.setStyle(Paint.Style.FILL);//充滿,即畫的幾何體為實心
    mPaintSmallCircle.setAntiAlias(true);
    mPaintLine = new Paint();
    mPaintLine.setColor(Color.GREEN);
    mPaintLine.setStyle(Paint.Style.STROKE);
    mPaintLine.setStrokeWidth(20);
    mPaintLine.setAntiAlias(true);
    mPaintText = new Paint();
    mPaintText.setColor(Color.WHITE);
    mPaintText.setTextAlign(Paint.Align.CENTER);//向中央對齊
    mPaintText.setTextSize(50);
    mPaintText.setAntiAlias(true);
    path = new Path();
    pointContainer = new HashMap<>();
    pointerSlipped = new ArrayList<>();
  }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
  }
  private float pivotX;//觸屏得到的x坐標
  private float pivotY;//觸屏得到的y坐標
  private float selectedX;//當前選中的圓點的x坐標
  private float selectedY;//當前選中的圓點的y坐標
  private float selectedXOld;//從前選中的圓點的x坐標
  private float selectedYOld;//從前選中的圓點的y坐標
  private boolean isHasMoved = false;//用於判斷path是否調用過moveTo()方法
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        pivotX = event.getX();
        pivotY = event.getY();
        //每次觸屏時需要清空一下pointerSlipped,即重置密碼
        pointerSlipped.clear();
        Log.d("pointTouched", pivotX + "," + pivotY);
        getSelectedPointIndex(pivotX, pivotY);
        invalidate();//重繪
        break;
      case MotionEvent.ACTION_MOVE:
        pivotX = event.getX();
        pivotY = event.getY();
        getSelectedPointIndex(pivotX, pivotY);
        invalidate();
        break;
      case MotionEvent.ACTION_UP:
        /**
         * 當手指離開屏幕時,重置path
         */
        path.reset();
        isHasMoved = false;
        String indexSequence = "";
        //打印出上一次手勢密碼的值
        for(int index:pointerSlipped){
          indexSequence += "/"+index;
        }
        Log.d("index",indexSequence);
        break;
    }
    invalidate();
    return true;
  }
  /**
   * 得到並存儲經過的圓點的序號
   * @param pivotX
   * @param pivotY
   */
  private void getSelectedPointIndex(float pivotX, float pivotY) {
    int index = 0;
    if (pivotX > patternMargin && pivotX < patternMargin + bigCircleRadius * 2) {
      if (pivotY > height / 2 && pivotY < height / 2 + bigCircleRadius * 2) {
        selectedX = pointContainer.get(1)[0];
        selectedY = pointContainer.get(1)[1];
        index = 1;
        Log.d("selectedPoint", selectedX + "," + selectedY);
      } else if (pivotY > height / 2 + added && pivotY < height / 2 + added + bigCircleRadius * 2) {
        selectedX = pointContainer.get(4)[0];
        selectedY = pointContainer.get(4)[1];
        index = 4;
      } else if (pivotY > height / 2 + added * 2 && pivotY < height / 2 + added * 2 + bigCircleRadius * 2) {
        selectedX = pointContainer.get(7)[0];
        selectedY = pointContainer.get(7)[1];
        index = 7;
      }
    } else if (pivotX > patternMargin + added && pivotX < patternMargin + added + bigCircleRadius * 2) {
      if (pivotY > height / 2 && pivotY < height / 2 + bigCircleRadius * 2) {
        selectedX = pointContainer.get(2)[0];
        selectedY = pointContainer.get(2)[1];
        index = 2;
      } else if (pivotY > height / 2 + added && pivotY < height / 2 + added + bigCircleRadius * 2) {
        selectedX = pointContainer.get(5)[0];
        selectedY = pointContainer.get(5)[1];
        index = 5;
      } else if (pivotY > height / 2 + added * 2 && pivotY <height / 2 + added * 2 + bigCircleRadius * 2) {
        selectedX = pointContainer.get(8)[0];
        selectedY = pointContainer.get(8)[1];
        index = 8;
      }
    } else if (pivotX > patternMargin + added * 2 && pivotX < patternMargin + added * 2 + bigCircleRadius * 2) {
      if (pivotY > height / 2 && pivotY < height / 2 + bigCircleRadius * 2) {
        selectedX = pointContainer.get(3)[0];
        selectedY = pointContainer.get(3)[1];
        index = 3;
      } else if (pivotY > height / 2 + added && pivotY < height / 2 + added + bigCircleRadius * 2) {
        selectedX = pointContainer.get(6)[0];
        selectedY = pointContainer.get(6)[1];
        index = 6;
      } else if (pivotY > height / 2 + added * 2 && pivotY < height / 2 + added * 2 + bigCircleRadius * 2) {
        selectedX = pointContainer.get(9)[0];
        selectedY = pointContainer.get(9)[1];
        index = 9;
      }
    }
    if (selectedX!=selectedXOld||selectedY!=selectedYOld){
      //當這次的坐標與上次的坐標不同時存儲這次點序號
      pointerSlipped.add(index);
      selectedXOld = selectedX;
      selectedYOld = selectedY;
      if (!isHasMoved){
        //當第一次觸碰到九個點之一時,path調用moveTo;
        path.moveTo(selectedX,selectedY);
        isHasMoved = true;
      }else{
        //path移動至當前圓點坐標
        path.lineTo(selectedX,selectedY);
      }
    }
  }
  private String text = "請繪制解鎖圖案";
  private float x;//繪制的圓形的x坐標
  private float y;//繪制圓形的縱坐標
  private float added;//水平豎直方向每個圓點中心間距
  private float patternMargin = 100;//九宮格距離邊界距離
  private float bigCircleRadius = 90;//外圓半徑
  private float smallCircleRadius = 25;//內圓半徑
  private int index;//圓點的序號
  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    added = (width - patternMargin * 2) / 3;
    x = patternMargin + added / 2;
    y = added / 2 + height / 2;
    index = 1;
    canvas.drawColor(Color.BLACK);
    canvas.drawText(text, width / 2, height / 4, mPaintText);
    /**
     * 繪制九個圓點圖案
     */
    for (int column = 0; column < 3; column++) {
      for (int row = 0; row < 3; row++) {
        canvas.drawCircle(x, y, bigCircleRadius, mPaintBigCircle);
        canvas.drawCircle(x, y, smallCircleRadius, mPaintSmallCircle);
        pointContainer.put(index, new Float[]{x, y});
        index++;
        x += added;
      }
      y += added;
      x = patternMargin + added / 2;
    }
    x = patternMargin + added / 2;
    y = added / 2 + height / 2;
    canvas.drawPath(path, mPaintLine);
  }
}

為什麼要規避重復?

因為在觸屏時,會調用很多次onTouchEvent()方法,這樣存儲的手勢密碼肯定會不准確,我在以上代碼中作出了處理,已經避免了重復,看打印信息:

這裡寫圖片描述

顯然,密碼沒有相鄰數重復,當然還有一種情況就是手指在兩個點之間來回等問題,這種狀況也需要避免,這裡沒有作處理。當然,我做得還不夠。。。

自定義view中用到的dp和px互相轉換的工具類:

public class SizeConvert {
  /**
   * 將dp轉換為sp
   */
  public static int dip2px(Context context, float dipValue){
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int)(dipValue * scale + 0.5f);
  }
  /**
   * sp轉dp
   */
  public static int px2dip(Context context, float pxValue){
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int)(pxValue / scale + 0.5f);
  }
}

主活動:

public class NineGridActivity extends BaseActivity{
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_nine_grid);
  }
}

layout中的布局文件view_nine_grid:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
  <com.test.shiweiwei.myproject.selfish_view.NineGridView
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</LinearLayout>

總結

我寫的只是最基本的九宮格滑動解密項目,實際用的九宮格解密比這個要復雜,有許多特效和其他更嚴謹的處理,事件的處理也不是這樣草草了事,如果想寫得漂亮,還得多花工夫。

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