Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂九宮格手勢密碼完整實作(含源碼下載)

編輯:關於 Android 程式設計

手勢密碼幾乎是每一支 Android 手機的標配功能,它用九個圓點串連出使用者記憶中的圖形,比數字密碼更直覺、也更有安全感。本文延續先前的自訂 UI 系列,帶大家從零打造一套可設置、可校驗的手勢密碼元件,並附上完整專案源碼。

源碼下載:https://xiazai.jb51.net/201610/yuanma/androidLock(jb51.net).rar

整體架構先來一次掃描

這套實作可以拆成五個角色:MainActivity 作為入口,負責在「設置」與「校驗」兩個流程之間跳轉;GestureContentView 是一個容器 ViewGroup,負責把九個圓點排版好;GestureDrawline 才是真正處理手勢軌跡與畫線的核心 View;GesturePoint 描述單一圓點的座標與狀態;GestureEditActivity 與 GestureVerifyActivity 則分別負責第一次設定與後續驗證。

一、首頁布局與入口邏輯

首頁只需要一個標題、兩個按鈕,一個負責設定、一個負責校驗。

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:textSize="24sp"
        android:text="手勢密碼" />
    <Button
        android:id="@+id/btn_set_lockpattern"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dip"
        android:text="設置手勢密碼" />
    <Button
        android:id="@+id/btn_verify_lockpattern"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="校驗手勢密碼" />
</LinearLayout> 

對應的 Activity 用最直白的 Intent 跳轉把兩個流程串起來:

 public class MainActivity extends Activity implements OnClickListener {
    private Button mBtnSetLock;
    private Button mBtnVerifyLock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpView();
        setUpListener();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_set_lockpattern:
                startActivity(new Intent(this, GestureEditActivity.class));
                break;
            case R.id.btn_verify_lockpattern:
                startActivity(new Intent(this, GestureVerifyActivity.class));
                break;
        }
    }
} 

二、兩個關鍵小工具

第一個是螢幕尺寸工具類,九宮格要依螢幕寬度做等分,勢必得先拿到寬高:

 public class AppUtil {
    public static int[] getScreenDispaly(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        return new int[] { width, height };
    }
} 

第二個是狀態常數。把「正常、選中、錯誤」三種狀態抽出來當常數,後面不管是畫點還是畫線都靠它判斷,可讀性會好很多。

 public class Constants {
    public static final int POINT_STATE_NORMAL = 0;   // 正常
    public static final int POINT_STATE_SELECTED = 1; // 已選中
    public static final int POINT_STATE_WRONG = 2;    // 錯誤
} 

三、用一個 Bean 描述一個圓點

GesturePoint 保存了圓點的上下左右邊界、中心座標、對應的 ImageView 以及序號。最巧妙的地方在 setPointState():狀態一被設定,就同步換掉背景圖,畫面與資料始終一致。

 public class GesturePoint {
    private int pointState;
    private int num;      // 從 1 開始,代表第幾個點
    private int leftX, rightX, topY, bottomY;
    private ImageView image;
    private int centerX, centerY;

    public GesturePoint(int leftX, int rightX, int topY, int bottomY, ImageView image, int num) {
        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 void setPointState(int state) {
        pointState = state;
        switch (state) {
            case Constants.POINT_STATE_NORMAL:
                image.setBackgroundResource(R.drawable.gesture_node_normal);
                break;
            case Constants.POINT_STATE_SELECTED:
                image.setBackgroundResource(R.drawable.gesture_node_pressed);
                break;
            case Constants.POINT_STATE_WRONG:
                image.setBackgroundResource(R.drawable.gesture_node_wrong);
                break;
        }
    }
    // getter / setter、hashCode、equals 略
} 

四、九宮格容器 GestureContentView

這個容器繼承 ViewGroup,在 addChild() 中把螢幕寬度三等分,用「第幾列、第幾行」算出九個圓點的位置,再交給 onLayout() 實際排版。這樣做的好處是:不管在什麼解析度上,九宮格永遠是正方形且居中。

 public class GestureContentView extends ViewGroup {
    private int[] screenDispaly;
    private int blockWidth;              // 螢幕寬度的 1/3
    private final int baseNum = 6;       // 圓點直徑佔據的比例
    private List<GesturePoint> list;
    private GestureDrawline gestureDrawline;

    public GestureContentView(Context context, boolean isVerify, String passWord,
                              GestureCallBack callBack) {
        super(context);
        screenDispaly = AppUtil.getScreenDispaly(context);
        blockWidth = screenDispaly[0] / 3;
        list = new ArrayList<GesturePoint>();
        addChild();
        gestureDrawline = new GestureDrawline(context, list, isVerify, passWord, callBack);
    }

    private void addChild() {
        for (int i = 0; i < 9; i++) {
            ImageView image = new ImageView(getContext());
            image.setBackgroundResource(R.drawable.gesture_node_normal);
            addView(image);
            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;
            list.add(new GesturePoint(leftX, rightX, topY, bottomY, image, i + 1));
        }
    }

    public void setParentView(ViewGroup parent) {
        LayoutParams lp = new LayoutParams(screenDispaly[0], screenDispaly[0]);
        setLayoutParams(lp);
        gestureDrawline.setLayoutParams(lp);
        parent.addView(gestureDrawline);
        parent.addView(this);
    }

    public void clearDrawlineState(long delayTime) {
        gestureDrawline.clearDrawlineState(delayTime);
    }
    // onLayout / onMeasure 依 blockWidth 重新計算每個子 View 的位置
} 

五、手勢繪製核心 GestureDrawline

這支 View 的責任最重:判斷手指壓在哪個點、要不要把「中間點」一起選中、怎麼畫線、錯誤時怎麼變紅、多久後自動清除。

自動補中間點的對照表

從 1 直接劃到 9,中間必然會經過 5,這是九宮格手勢公認的規則。實作方式是先建一張 key 為「小點,大點」的 HashMap:

 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));
} 

觸摸事件的三段式處理

ACTION_DOWN 決定起點,ACTION_MOVE 負責連線與補中間點,ACTION_UP 則把 StringBuilder 中累積的序號串交出去比對。手指抬起後,根據 isVerify 走校驗分支或設定分支。

 @Override
public boolean onTouchEvent(MotionEvent event) {
    if (!isDrawEnable) 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());
            }
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            clearScreenAndDrawList();
            GesturePoint pointAt = getPointAt((int) event.getX(), (int) event.getY());
            // 畫線、補中間點、更新 currentPoint ...
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            if (isVerify) {
                if (passWord.equals(passWordSb.toString())) {
                    callBack.checkedSuccess();
                } else {
                    callBack.checkedFail();
                }
            } else {
                callBack.onGestureCodeInput(passWordSb.toString());
            }
            break;
    }
    return true;
} 

錯誤路徑與延遲清除

錯誤時把整條路徑重畫成暗紅色,並透過 Handler.postDelayed() 延遲清除,讓使用者有時間看清自己哪裡畫錯了。

 public void clearDrawlineState(long delayTime) {
    if (delayTime > 0) {
        isDrawEnable = false;
        drawErrorPathTip();          // paint 改成 Color.rgb(154, 7, 21)
    }
    new Handler().postDelayed(new clearStateRunnable(), delayTime);
}

final class clearStateRunnable implements Runnable {
    public void run() {
        passWordSb = new StringBuilder();
        lineList.clear();
        clearScreenAndDrawList();
        for (GesturePoint p : list) {
            p.setPointState(Constants.POINT_STATE_NORMAL);
        }
        invalidate();
        isDrawEnable = true;
    }
} 

對外只暴露一個回呼介面,讓 Activity 不必關心繪製細節:

 public interface GestureCallBack {
    void onGestureCodeInput(String inputCode); // 使用者完成一次輸入
    void checkedSuccess();                     // 校驗通過
    void checkedFail();                        // 校驗失敗
} 

六、設定流程 GestureEditActivity

設定流程的核心是「兩次輸入必須一致」。第一次輸入暫存密碼並清空畫面,第二次比對成功就結束 Activity,失敗則播放左右晃動動畫提示。

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#48423D">
    <RelativeLayout android:id="@+id/top_layout"
        android:layout_width="match_parent" android:layout_height="46dip"
        android:background="#000000" android:layout_alignParentTop="true">
        <TextView android:id="@+id/text_title"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_centerInParent="true" android:text="@string/setup_gesture_code"
            android:textSize="20sp" android:textColor="#ffffff" />
    </RelativeLayout>
    <LinearLayout android:id="@+id/gesture_tip_layout"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_below="@id/top_layout" android:gravity="center">
        <TextView android:id="@+id/text_tip"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:gravity="center_horizontal" android:text="@string/set_gesture_pattern"
            android:textColor="#F98F12" android:layout_marginTop="10dip" />
    </LinearLayout>
    <FrameLayout android:id="@+id/gesture_container"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_below="@id/gesture_tip_layout" android:layout_marginTop="20dip" />
    <TextView android:id="@+id/text_reset"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_below="@id/gesture_container" android:layout_marginTop="20dip"
        android:gravity="center_horizontal" android:text="@string/set_gesture_pattern_reason"
        android:textColor="#816E6A" />
</RelativeLayout> 
 public class GestureEditActivity extends Activity implements OnClickListener {
    private TextView mTextTip, mTextReset;
    private FrameLayout mGestureContainer;
    private GestureContentView mGestureContentView;
    private boolean mIsFirstInput = true;
    private String mFirstPassword = null;

    /** 至少連接 4 個點才算合法密碼 */
    private boolean isInputPassValidate(String inputPassword) {
        return !TextUtils.isEmpty(inputPassword) && inputPassword.length() >= 4;
    }

    private void setUpViews() {
        mTextTip = findViewById(R.id.text_tip);
        mTextReset = findViewById(R.id.text_reset);
        mTextReset.setClickable(false);
        mGestureContainer = findViewById(R.id.gesture_container);

        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;
                    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();
                    finish();
                } else {
                    mTextTip.setText(Html.fromHtml(
                        "<font color='#c70c1e'>與上一次繪制不一致,請重新繪制</font>"));
                    mTextTip.startAnimation(
                        AnimationUtils.loadAnimation(GestureEditActivity.this, R.anim.shake));
                    mGestureContentView.clearDrawlineState(1300L);
                }
                mIsFirstInput = false;
            }
            @Override public void checkedSuccess() { }
            @Override public void checkedFail() { }
        });
        mGestureContentView.setParentView(mGestureContainer);
    }
} 

七、校驗流程 GestureVerifyActivity

校驗頁更單純:把 isVerify 設為 true,並把要比對的密碼字串傳進去,剩下的交給 GestureDrawline 完成。

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:background="#48443c">
    <LinearLayout android:id="@+id/gesture_tip_layout"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:orientation="vertical" android:paddingTop="20dip">
        <TextView android:id="@+id/text_tip"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_marginTop="10dip" android:gravity="center_horizontal"
            android:textColor="#000000" android:visibility="invisible" />
    </LinearLayout>
    <FrameLayout android:id="@+id/gesture_container"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_below="@id/gesture_tip_layout" />
</RelativeLayout> 
 public class GestureVerifyActivity extends Activity {
    private TextView mTextTip;
    private FrameLayout mGestureContainer;
    private GestureContentView mGestureContentView;

    private void setUpViews() {
        mTextTip = findViewById(R.id.text_tip);
        mGestureContainer = findViewById(R.id.gesture_container);

        mGestureContentView = new GestureContentView(this, true, "12589", new GestureCallBack() {
            @Override public void onGestureCodeInput(String inputCode) { }

            @Override public void checkedSuccess() {
                mGestureContentView.clearDrawlineState(0L);
                Toast.makeText(GestureVerifyActivity.this, "密碼正確", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override public void checkedFail() {
                mGestureContentView.clearDrawlineState(1300L);
                mTextTip.setVisibility(View.VISIBLE);
                mTextTip.setText(Html.fromHtml("<font color='#c70c1e'>密碼錯誤</font>"));
                mTextTip.startAnimation(
                    AnimationUtils.loadAnimation(GestureVerifyActivity.this, R.anim.shake));
            }
        });
        mGestureContentView.setParentView(mGestureContainer);
    }
} 

八、別忘了那個晃動動畫

提示文字左右搖晃是很常見的錯誤回饋手法,用一個 translate 搭配循環插值器就足夠:

 <?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="https://schemas.android.com/apk/res/android"
    android:fromXDelta="0" android:toXDelta="10"
    android:duration="120"
    android:interpolator="@android:anim/cycle_interpolator"
    android:repeatMode="restart" android:repeatCount="2"/> 

延伸閱讀與小結

想對照閱讀的話,可以搭配這兩篇:手勢密碼簡單版與手勢密碼改進版。整份實作最值得學習的三點是:以狀態常數統一管理圓點外觀、以 HashMap 優雅處理「中間點自動選中」、以及用延遲 Runnable 讓錯誤回饋有足夠的可視時間。真正上線時,記得別把密碼以純文字存在本地,至少要做過 hash 與加鹽處理。

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved