首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android EditText 結合 phone 輸入類型與 password 遮罩顯示

     編輯:程式設計綜合問答

需求:輸入電話號碼時顯示數字鍵盤(inputType="phone"),同時字元以密碼圓點遮罩顯示(inputType="textPassword")。兩者屬不同 InputType 旗標,無法直接用 | 組合。解決方案:使用 android:password="true" (舊屬性) 搭配 inputType="phone",或程式碼動態設定 TransformationMethod。

方案一:XML 混合屬性(相容舊版,簡單)



    />

注意:android:password 為舊屬性,未來版本可能移除,但目前仍廣泛支援。

方案二:程式碼動態設定 TransformationMethod(現代、可控)


EditText editText = findViewById(R.id.phoneInput);
// 設定電話鍵盤
editText.setInputType(InputType.TYPE_CLASS_PHONE);
// 設定密碼遮罩(可切換顯示/隱藏)
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());

// 切換顯示明文
editText.setTransformationMethod(null);
// 或使用內建切換
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());

方案三:自訂 TransformationMethod(進階,如只遮罩後 4 碼)


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 子類別自訂。
  • 無障礙服務(TalkBack)在密碼模式下會朗讀「星號」而非實際字元。

結合 inputType="phone" 與 PasswordTransformationMethod,即能同時擁有數字鍵盤便利性與密碼遮罩安全性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved