使用Android自訂控制項實現滑動解鎖九宮格_Android

來源:互聯網
上載者:User

本文概述:

 滑動解鎖九宮格的分析:

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>

總結

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.