本文实例展示了Android实现动态显示或隐藏密码输入框内容的方法,分享给大家供大家参考之用。具体方法如下:
该功能可通过设置EditText的setTransformationMethod()方法来实现隐藏密码或者显示密码。
示例代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout xmlns:android = "http://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 >
|
希望本文所述对大家的Android程序设计有所帮助。