編輯:關於 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
Android 特效專輯(八)——打造心型氣泡飛舞特效,讓你的 App 瞬間暖心
Android 特效專輯(八)——實現心型氣泡飛舞的特效,讓你的 APP 瞬間暖心 馬上也要放年假了,家裡估計會沒網,更完這篇可能要到年後了。
Android Handler 完全指南:訊息機制原理與兩個實作範例
做 Android 開發時,Handler 大概是出現頻率最高的類別之一。它的重要性不必多說,但真正能把原理講清楚的文章並不多。本文就從基本概念出發,再用兩個範例把用法走
淺談 FloatingActionButton:Material 風格懸浮按鈕完整用法
淺談 FloatingActionButton:Material 風格懸浮按鈕完整用法 一、介紹 FloatingActionButton(懸浮操作按鈕)是 Materi
Navigation Drawer 實作全解:從 DrawerLayout 到 ActionBarDrawerToggle
抽屜式導航欄(Navigation Drawer)是顯示在螢幕左緣的主導航面板。大部分時間隱藏,當使用者從左緣往右滑動時才會出現;在應用程式頂層,點擊 ActionBar