TIP: How to Show and Hide Text in EditText
In this TIP, we learn how to show (password) and hide (*******) text in EditText programatically. Here is the code that does this magical transformation.
// CHECKBOX HIDE HANDLER
final CheckBox cb= (CheckBox)d.findViewById(R.id.CheckBoxHide);
cb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (cb.isChecked()) {
editTextPasswordFirst.setTransformationMethod(new PasswordTransformationMethod());
editTextPasswordSecond.setTransformationMethod(new PasswordTransformationMethod());
}
else {
editTextPasswordFirst.setTransformationMethod(null);
editTextPasswordSecond.setTransformationMethod(null);
}
}
});
Here is another version using the conditional ? operator:
// CHECKBOX HIDE HANDLER
final CheckBox checkBoxHide= (CheckBox)findViewById(R.id.CheckBoxHide);
checkBoxHide.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PasswordTransformationMethod transform= (checkBoxHide.isChecked()) ?
new PasswordTransformationMethod() : null;
editTextPasswordFirst.setTransformationMethod(transform);
editTextPasswordSecond.setTransformationMethod(transform);
}
});
I am conflicted. The second version is seems more efficient, but the first version is easier to read.
These changes may not "stick" on a change in phone orientation. If so, you can try setting the desired behavior in onResume.
Hope that helps,
JAL