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

Android 自定義軟鍵盤實作:打造專屬的密碼輸入鍵盤

編輯:關於 Android 程式設計

下面示範如何在 Android 中實作一個自定義的軟鍵盤,特別針對密碼輸入場景做了一些客製化處理,例如按鍵隨機排列、輸入內容短暫顯示後變為星號等。

圖一為搜狗輸入法、圖二與圖三為自定義的密碼鍵盤。

一、自定義輸入框 LPTextField

這個類別繼承自 EditText,透過覆寫 dispatchTouchEvent,在點擊時隱藏系統軟鍵盤、改為彈出自定義鍵盤,並套用密碼轉換。

public class LPTextField extends EditText {
    private MainActivity bv_;
    String password_ = "password";

    public LPTextField(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTransformationMethod(new PasswordTransformationMethod());
        bv_ = (MainActivity) context;
        bv_.inputManager_ = (InputMethodManager) bv_.getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    public boolean dispatchTouchEvent(MotionEvent event) {
        this.requestFocus();
        boolean rt = false;
        if (null != password_ && password_.equalsIgnoreCase(password)) {
            bv_.inputManager_.hideSoftInputFromWindow(this.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            if (bv_.dlg == null || !bv_.dlg.isShowing()) {
                if (this.isEnabled()) {
                    bv_.OnCreateInputWindow(this);
                    rt = true;
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }
}

二、自定義鍵盤 LPKeyBoard

這個類別繼承自 LinearLayout,內部包含一個顯示輸入內容的 tempEdit_、確定按鈕 btnOK_,以及核心的鍵盤繪製檢視 LPImfView。

public class LPKeyBoard extends LinearLayout {
    private Dialog dlg_;
    LPImfView imfView;
    MainActivity bv_;
    EditText tempEdit_;
    buttonOk btnOK_;
    boolean inputTypeNumber_ = false;
    int maxSize;
    private Vibrator vibrator_;
    private static final long VIBRATE_DURATION = 30L;

    public LPKeyBoard(Context context, LPTextField text) {
        super(context);
        bv_ = (MainActivity) context;
        btnOK_ = new buttonOk(context, false);
        tempEdit_ = new EditText(context);
        tempEdit_.setTextSize(15);
        tempEdit_.setHeight(text.getHeight() - 10);
        tempEdit_.setFocusable(false);
        tempEdit_.setBackgroundResource(R.drawable.bg_edittext);
        vibrator_ = (Vibrator) bv_.getSystemService(Context.VIBRATOR_SERVICE);
        tempEdit_.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        if (text.getInputType() == android.text.InputType.TYPE_CLASS_NUMBER) {
            inputTypeNumber_ = true;
        }
        // 依輸入類型決定版面配置
        if (inputTypeNumber_) {
            tempEdit_.setLayoutParams(new LinearLayout.LayoutParams(LPUtils.screenWidth_, LayoutParams.WRAP_CONTENT));
            this.addView(tempEdit_);
        } else {
            tempEdit_.setLayoutParams(new LinearLayout.LayoutParams(LPUtils.screenWidth_ * 4 / 5, LayoutParams.WRAP_CONTENT));
            LinearLayout ll = new LinearLayout(context);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            ll.addView(tempEdit_);
            LayoutParams lp = new LayoutParams(LPUtils.screenWidth_ / 5 - LPUtils.getScaledValue(6), text.getHeight() - 10);
            ll.addView(btnOK_, lp);
            this.addView(ll);
        }
        if (null != text.getHint()) { tempEdit_.setHint(text.getHint()); }
        imfView = new LPImfView(context, text);
        this.addView(imfView);
        requestFocus();
        this.setClickable(true);
        this.setBackgroundResource(R.drawable.keyboard_bg);
        this.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        this.setOrientation(LinearLayout.VERTICAL);
    }
}

三、鍵盤繪製檢視 LPImfView

這是全篇最關鍵的部分。它繼承自 TextView,透過 onDraw 自行把字母鍵、數字鍵、功能鍵一顆顆畫出來,並在 onTouchEvent 中依觸摸座標判斷按了哪一顆鍵。

class LPImfView extends TextView {
    private EditText edit_;
    private Paint paint_, textPaint_;
    private int key_row = -1;    // 標記按鍵列
    private int key_column = -1; // 標記按鍵行
    private long keyDownTime;
    private StringBuffer textBuffer_;
    // 鍵盤字母表
    private final char[] keyAbc_ = { 'q','w','e','r','t','y','u','i','o','p',
        'a','s','d','f','g','h','j','k','l',
        'z','x','c','v','b','n','m' };
    // 大小寫、數字/字母、按鍵狀態等標記
    boolean isABC_, isNum_, keyEnter_, isDel_, isDelete_;

    public LPImfView(Context context, LPTextField text) {
        super(context);
        edit_ = text;
        maxSize = text.maxSize_;
        setFocusable(true);
        requestFocus();
        init();
    }

    // onDraw 中依 isNum_ 決定畫數字鍵盤還是字母鍵盤,逐顆 drawBitmap 並 drawText
    public void onDraw(Canvas g) {
        drawKeyBoard(g);
    }

    @Override public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 依 y 座標判斷落在第幾列,依 x 座標判斷第幾行,記下 key_row / key_column
                ...
                invalidate();
                return true;
            case MotionEvent.ACTION_UP:
                // 依 key_row / key_column 決定輸入哪個字元、切換大小寫、切換數字鍵或刪除
                ...
                // 每按一次鍵就刷新一次
                column1 = column2 = column3 = -1;
                tempEdit_.setText(getStringBuffer(textBuffer_, true).toString());
                // 使用者輸入的內容顯示一秒後變為 * 號
                new CountDownTimer(1000, 1000) {
                    public void onFinish() {
                        tempEdit_.setText(getStringBuffer(textBuffer_, false).toString());
                    }
                    public void onTick(long millisUntilFinished) {}
                }.start();
                edit_.setText(textBuffer_);
                vibrator_.vibrate(2 * VIBRATE_DURATION);
                invalidate();
                return true;
        }
        return false;
    }

    // 把輸入內容拼成顯示字串:isShow 為 true 時最後一個字顯示實際內容,其餘顯示 *
    public StringBuffer getStringBuffer(StringBuffer text, boolean isShow) { ... }

    // 連刪:按下超過 0.1 秒即連續刪除
    public void delEditAgainValue() {
        if ((System.currentTimeMillis() - keyDownTime) / 100 > 1) {
            delEditValue(textBuffer_);
        }
    }
}

四、幾個設計亮點

這個自定義鍵盤有幾個值得借鏡的做法:

1. 按鍵隨機排列:透過 getRandomNumber() 打亂字母與數字的順序(resultAbc、resultNum),增加輸入安全性。

2. 密碼短暫可見:每次輸入後,內容會先顯示一秒,再用 CountDownTimer 把已輸入部分變回星號,兼顧正確性確認與安全性。

3. 觸壓回饋:每次按鍵觸發 Vibrator 震動,提升輸入手感。

4. 自繪按鍵狀態:完全透過 onDraw 手繪按鍵的按下/正常兩種狀態,自由度極高,但也意味著座標計算需要仔細對齊。

整體而言,自定義軟鍵盤的核心是「自繪 + 座標命中判斷」。只要把每一顆按鍵的矩形區域算準,並在 ACTION_UP 時對應到正確的輸入邏輯,就能打造出一個完全客製化的輸入體驗。

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