本文共 2149 字,大约阅读时间需要 7 分钟。
Android Password EditText显示和隐藏密码的实现方法
在Android开发中,当需要设置密码输入框为显示和隐藏模式时,可以通过以下方法实现。首先需要在 XML 资源文件中定义EditText控件,将其设置为密码类型,确保不显示实际输入的文本。需要注意的是,EditText默认的TransformationMethod是PasswordTransformationMethod,这会使密码在输入时显示为星号或圆点。
为了实现密码框显示和隐藏切换功能,可以在EditText的父容器中添加一个CompoundButton,用于控制TransformationMethod的切换。以下是实现步骤:
// 1. 在布局文件中定义CompoundButton和EditText CompoundButton checkBox = (CompoundButton) findViewById(R.id.password_show_hide); EditText passwordEditText = (EditText) findViewById(R.id.password_edit);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // 根据isChecked判断是否显示或隐藏密码 if (isChecked) { // 显示密码 passwordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); } else { // 隐藏密码 passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); } }});
在Android XML布局文件中,通过设置android:inputType="textPassword"
可以确保 EditText默认显示为密码类型,这样可以显示星号或圆点而非真实字符。同时,为了避免EditText占据焦点,可以通过设置android:focusable="false"
来实现,这样可以防止其他控件的一些交互问题。
以下是一个完整的实现代码示例,供参考:
// 在Activity中设置TransformationMethodboolean isChecked = false;CheckBox displayCheckbox = new CheckBox(this);displayCheckbox.setText("显示密码");displayCheckbox.setId(R.id.display_password_checkbox);displayCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // 显示密码 passwordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); } else { // 隐藏密码 passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); } }});
通过以上方法,可以轻松实现Android EditText的显示和隐藏密码功能。
转载地址:http://ylgez.baihongyu.com/