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

Android EditText 密碼輸入框屬性設置:inputType="password" 核心配置

     編輯:程式設計疑難解答

核心屬性

<EditText
    android:id="@+id/et_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="請輸入密碼"
    android:inputType="textPassword"  <!-- 關鍵:密碼模式,顯示圓點/星號 -->
    android:maxLines="1"               <!-- 單行 -->
    android:singleLine="true"          <!-- 兼容舊版單行屬性 -->
    android:textSize="16sp"            <!-- 字體大小 sp -->
    android:padding="12dp"             <!-- 內邊距 -->
    android:background="@drawable/bg_edittext" <!-- 自定義背景 (可選) --> />

關鍵屬性詳解

屬性值作用
android:inputTypetextPassword 或 textVisiblePassword核心:前者顯示圓點 ●,後者可顯示明文 (通常配合「顯示密碼」開關)。
舊版 textPassword 等同 numberPassword 但允許字母符號。
android:maxLines / singleLine1 / true強制單行,防止換行輸入。
android:fontFamilymonospace等寬字體,密碼圓點對齊更美觀 (可選)。
android:importantForAutofillno禁用系統自動填充彈窗干擾 (API 26+,可選)。

進階:顯示/隱藏密碼切換 (Material Design 標準)

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true" <!-- 內置顯示/隱藏圖標 -->
    app:passwordToggleTint="@color/colorPrimary" <!-- 圖標顏色 -->
    app:hintEnabled="true">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="密碼"
        android:inputType="textPassword" />

</com.google.android.material.textfield.TextInputLayout>

依賴: implementation 'com.google.android.material:material:1.9.0+'。無需手寫圖標切換邏輯,體驗最佳。

代碼中動態設置


EditText etPwd = findViewById(R.id.et_password);
// 設置密碼模式
etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
// 切換顯示/隱藏
etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance()); // 隱藏
etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); // 顯示明文
// 光標移至末尾
etPwd.setSelection(etPwd.getText().length());

總結

Android 密碼輸入框核心屬性:android:inputType="textPassword"。 配合 maxLines="1"、TextInputLayout 內置開關、自定義背景/字體,即可實現標準、安全、美觀的密碼輸入體驗。

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