需求:輸入電話號碼時顯示數字鍵盤(inputType="phone"),同時字元以密碼圓點遮罩顯示(inputType="textPassword")。兩者屬不同 InputType 旗標,無法直接用 | 組合。解決方案:使用 android:password="true" (舊屬性) 搭配 inputType="phone",或程式碼動態設定 TransformationMethod。
/>
注意:android:password 為舊屬性,未來版本可能移除,但目前仍廣泛支援。
EditText editText = findViewById(R.id.phoneInput);
// 設定電話鍵盤
editText.setInputType(InputType.TYPE_CLASS_PHONE);
// 設定密碼遮罩(可切換顯示/隱藏)
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
// 切換顯示明文
editText.setTransformationMethod(null);
// 或使用內建切換
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
public class PartialMaskTransformationMethod extends PasswordTransformationMethod {
private final int visibleSuffixLength;
public PartialMaskTransformationMethod(int visibleSuffixLength) {
this.visibleSuffixLength = visibleSuffixLength;
}
@Override
public CharSequence getTransformation(CharSequence source, View view) {
if (source.length() <= visibleSuffixLength) return source;
StringBuilder masked = new StringBuilder();
for (int i = 0; i < source.length() - visibleSuffixLength; i++) {
masked.append('•'); // 或 getPasswordChar()
}
masked.append(source.subSequence(source.length() - visibleSuffixLength, source.length()));
return masked;
}
}
// 使用:只顯示後 4 碼
editText.setTransformationMethod(new PartialMaskTransformationMethod(4));
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| android:password="true" | XML 宣告式、零代碼 | 舊屬性、無法動態切換 | 固定遮罩需求 |
| PasswordTransformationMethod | 可動態切換、標準 API | 需代碼設定 | 顯示/隱藏切換按鈕 |
| 自訂 TransformationMethod | 完全控制遮罩邏輯 | 實作複雜 | 部分遮罩、特殊字元 |
EditText etPhone = findViewById(R.id.etPhone);
ImageView ivToggle = findViewById(R.id.ivToggle);
boolean isPassword = true;
etPhone.setTransformationMethod(PasswordTransformationMethod.getInstance());
ivToggle.setOnClickListener(v -> {
isPassword = !isPassword;
if (isPassword) {
etPhone.setTransformationMethod(PasswordTransformationMethod.getInstance());
ivToggle.setImageResource(R.drawable.ic_visibility_off);
} else {
etPhone.setTransformationMethod(null);
ivToggle.setImageResource(R.drawable.ic_visibility);
}
// 保持游標在末尾
etPhone.setSelection(etPhone.getText().length());
});
inputType="phone" 僅影響軟鍵盤佈局,不限制輸入字元(使用者仍可貼上字母)。• (U+2022),可透過 android:passwordChar 或 PasswordTransformationMethod 子類別自訂。結合 inputType="phone" 與 PasswordTransformationMethod,即能同時擁有數字鍵盤便利性與密碼遮罩安全性。