Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Rajkiran picture Rajkiran · Mar 27, 2012 · Viewed 197.1k times · Source

In my application, I have an EditText whose default input type is set to android:inputType="textPassword" by deault. It has a CheckBox to its right, which is when checked, changes the input type of that EditText to NORMAL PLAIN TEXT. Code for that is

password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

My problem is, when that CheckBox is unchecked it should again set the input type to PASSWORD. I've done it using-

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

But, the text inside that edittext is still visible. And for surprise, when I change the orienatation, it automatically sets the input type to PASSWORD and the text inside is bulleted (shown like a password).

Any way to achieve this?

Answer

Rajkiran picture Rajkiran · Mar 27, 2012

Add an extra attribute to that EditText programmatically and you are done:

password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

For numeric password (pin):

password.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

Also, make sure that the cursor is at the end of the text in the EditText because when you change the input type the cursor will be automatically set to the starting point. So I suggest using the following code:

et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
et_password.setSelection(et_password.getText().length());

When using Data Binding, you can make use of the following code:

<data>
        <import type="android.text.InputType"/>
.
.
.
<EditText
android:inputType='@{someViewModel.isMasked ? 
(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) :
InputType.TYPE_CLASS_TEXT }'

If using Kotlin:

password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD