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

自訂 View 密碼輸入框的完整實作思路

編輯:關於 Android 開發

設計準則

寫自訂 View 時有一條值得奉行的原則:把凡是會影響外觀與行為的屬性全部暴露出來,讓使用者可以透過 XML 添加和設置樣式,透過元素屬性控制外觀與行為,並提供監聽器與重要事件通信。這樣自訂 View 才真正像一個合格的系統控件,而不是一段只能複製貼上的代碼。

關於自訂 View 的通用步驟,可參閱相關專題文章,本文聚焦於密碼輸入框這個具體案例。

最終效果

支持的樣式屬性

可透過 XML 定義、用以影響外觀與行為的屬性如下:

  • 邊框圓角值、邊框顏色、邊框寬度
  • 分割線顏色
  • 密碼位數、密碼圓點大小、密碼圓點顏色

對應的 declare-styleable 定義:

<declare-styleable name="PasswordInputView">
    <attr name="borderWidth"    format="dimension"/>
    <attr name="borderColor"    format="color"/>
    <attr name="borderRadius"   format="dimension"/>
    <attr name="passwordLength" format="integer"/>
    <attr name="passwordWidth"  format="dimension"/>
    <attr name="passwordColor"  format="color"/>
    <attr name="passwordRadius" format="dimension"/>
</declare-styleable>

除此之外,它同時保留原生 EditText 的能力——可以取得輸入的值、可以設置數字鍵盤等,這點對實際使用至關重要。

繪制邏輯

protected void onDraw(Canvas canvas) {
    int width  = getWidth();
    int height = getHeight();

    // 外邊框
    RectF rect = new RectF(0, 0, width, height);
    borderPaint.setColor(borderColor);
    canvas.drawRoundRect(rect, borderRadius, borderRadius, borderPaint);

    // 內容區
    RectF rectIn = new RectF(rect.left   + defaultContMargin,
                             rect.top    + defaultContMargin,
                             rect.right  - defaultContMargin,
                             rect.bottom - defaultContMargin);
    borderPaint.setColor(Color.WHITE);
    canvas.drawRoundRect(rectIn, borderRadius, borderRadius, borderPaint);

    // 分割線
    borderPaint.setColor(borderColor);
    borderPaint.setStrokeWidth(defaultSplitLineWidth);
    for (int i = 1; i < passwordLength; i++) {
        float x = width * i / passwordLength;
        canvas.drawLine(x, 0, x, height, borderPaint);
    }

    // 密碼圓點
    float cx, cy = height / 2;
    float half = width / passwordLength / 2;
    for (int i = 0; i < textLength; i++) {
        cx = width * i / passwordLength + half;
        canvas.drawCircle(cx, cy, passwordWidth, passwordPaint);
    }
}

這段代碼的結構值得細看:先畫外框,再畫內縮一層的白色內容區形成邊框視覺,接著按位數均分畫出分割線,最後依據實際已輸入的位數 textLength 畫出相應數量的圓點。

幾處實現細節值得注意。cy = height / 2 讓圓點垂直居中;half 這一步是關鍵——若直接用 width * i / passwordLength 作為圓心 x 座標,圓點會落在每格的左邊界上而非中央,加上半格偏移後才對齊格子中心。另外,圓點數量由 textLength 而非 passwordLength 控制,這樣才能實現「輸入幾位就顯示幾個點」的效果。

還有一點實務上的建議:既然要繼承 EditText 並自繪內容,就需要在 onMeasure 中正確處理測量邏輯,並在 onTextChanged 中同步更新 textLength 後呼叫 invalidate() 觸發重繪。此外,記得把 cursorVisible 設為 false,否則系統游標會與自繪的圓點重疊。

完整代碼

https://github.com/tianshaojie/Android-PasswordInputView

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