Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 密碼欄位的顯示與隱藏切換

編輯:關於 Android 程式設計

登入頁面上幾乎都會有一個「顯示密碼」的勾選框,讓使用者確認自己沒有打錯字。在 Android 裡實作這個功能其實只需要兩個 TransformationMethod,加上一個 CheckBox 的狀態監聽而已。

一、版面配置 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword">
        <requestFocus />
    </EditText>

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="顯示密碼" />

</LinearLayout>

關鍵在 android:inputType="textPassword",系統預設就會把輸入內容轉為圓點顯示。

二、MainActivity.java

public class MainActivity extends Activity {

    private TextView editText1;
    private CheckBox checkBox1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText1 = (TextView) findViewById(R.id.editText1);
        checkBox1 = (CheckBox) findViewById(R.id.checkBox1);

        checkBox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 勾選:顯示明文
                    editText1.setTransformationMethod(
                            HideReturnsTransformationMethod.getInstance());
                } else {
                    // 取消勾選:恢復掩碼
                    editText1.setTransformationMethod(
                            PasswordTransformationMethod.getInstance());
                }
            }
        });
    }
}

三、原理說明

真正做切換的只有這兩行:

editText1.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
editText1.setTransformationMethod(PasswordTransformationMethod.getInstance());

TransformationMethod 是 TextView 用來決定「顯示時要不要改寫文字外觀」的策略。PasswordTransformationMethod 把每個字元換成掩碼符號,HideReturnsTransformationMethod 則只隱藏換行符號、其他照原樣顯示,因此被拿來當作「顯示密碼」的替身。因為它並不會改動 EditText 背後實際儲存的字串,密碼值完全不會受影響。

順帶一提,這裡把 editText1 宣告成 TextView 而非 EditText 也沒問題,因為 setTransformationMethod 是定義在父類別 TextView 上的方法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved