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

Android實作:動態顯示或隱藏密碼輸入框內容

編輯:關於 Android 程式設計

許多App都提供了「小眼睛」按鈕,讓使用者在輸入密碼時能自由切換明文與密文顯示。本文將示範如何實作這個實用的小功能,分享給大家參考。

這個功能可透過設定 EditText 的 setTransformationMethod() 方法來實現:使用 HideReturnsTransformationMethod 顯示明文,使用 PasswordTransformationMethod 則以「.」遮罩密碼。

示例程式碼如下:

 private Button mBtnPassword; private EditText mEtPassword; private boolean mbDisplayFlg = false; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mEtPassword = (EditText)findViewById(R.id.password); mBtnPassword = (Button)findViewById(R.id.btnPassword); mBtnPassword.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Log.d("AndroidTest", "mbDisplayFlg = " + mbDisplayFlg); if (!mbDisplayFlg) { // display password text, for example "123456" mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); } else { // hide password, display "." mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance()); } mbDisplayFlg = !mbDisplayFlg; mEtPassword.postInvalidate(); } }); } 

對應的 main.xml 佈局檔如下:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/btnPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密碼" /> <EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:password="true" android:textSize="18sp" android:text="123456"> </EditText> </LinearLayout> 

這裡的關鍵在於以一個布林變數 mbDisplayFlg 記錄目前的顯示狀態,每次點擊按鈕時就切換 TransformationMethod,並呼叫 postInvalidate() 讓畫面重新繪製。這個小小的互動細節,能顯著提升使用者輸入密碼時的操作體驗。

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