<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:inputType | textPassword 或 textVisiblePassword | 核心:前者顯示圓點 ●,後者可顯示明文 (通常配合「顯示密碼」開關)。 舊版 textPassword 等同 numberPassword 但允許字母符號。 |
android:maxLines / singleLine | 1 / true | 強制單行,防止換行輸入。 |
android:fontFamily | monospace | 等寬字體,密碼圓點對齊更美觀 (可選)。 |
android:importantForAutofill | no | 禁用系統自動填充彈窗干擾 (API 26+,可選)。 |
<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 內置開關、自定義背景/字體,即可實現標準、安全、美觀的密碼輸入體驗。