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

In my application, I have an EditText whose default input type is set to android:inputType="textPassword" by default. 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 orientation, it automatically sets the input type to PASSWORD and the text inside is bulleted (shown like a password).

Any way to achieve this?

This question is related to android passwords android-edittext

The answer is


Checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // checkbox status is checked.
                if (isChecked) {
                        //password is visible
 PasswordField.setTransformationMethod(HideReturnsTransformationMethod.getInstance());     
                } else {
                        //password gets hided
             passwordField.setTransformationMethod(PasswordTransformationMethod.getInstance());       
                }
            }
        });

The Password Visibility Toggle feature has been added to support library version 24.2.0 enabling you to toggle the password straight from the EditText without the need for a CheckBox.

You can make that work basically by first updating your support library version to 24.2.0 and then setting an inputType of password on the TextInputEditText. Here's how to do that:

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password"
            android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>

You can get more information about the new feature on the developer documentation for TextInputLayout.


Complete code when you want to apply the Password visibility in Password edit text.

Create a handle [ Any drawable or Checkbox]

on click or on Checked/Uncheck write this:

 if (edittext.getInputType() == (InputType.TYPE_CLASS_TEXT |
                    InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD )){

                edittext.setInputType(InputType.TYPE_CLASS_TEXT |
                        InputType.TYPE_TEXT_VARIATION_PASSWORD );
            }else{
                edittext.setInputType(InputType.TYPE_CLASS_TEXT |
                        InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );
            }

Do not forget to write this line:

 edittext.setSelection(edittext.getText().length());

It resets the cursor to the end of line.


Blockquote

final int[] count = {0};

    showandhide.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(count[0] ==0)
            {
                password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                count[0]++;
            }
            else {

                password.setInputType(InputType.TYPE_CLASS_TEXT |
                        InputType.TYPE_TEXT_VARIATION_PASSWORD);
                showandhide.setText("Hide");
                count[0]--;
            }

        }
    });

Based on answers of neeraj t and Everton Fernandes Rosario I wrote in Kotlin, where password is an id of an EditText in your layout.

// Show passwords' symbols.
private fun showPassword() {
    password.run {
        val cursorPosition = selectionStart
        transformationMethod = HideReturnsTransformationMethod.getInstance()
        setSelection(cursorPosition)
    }
}

// Show asterisks.
private fun hidePassword() {
    password.run {
        val cursorPosition = selectionStart
        transformationMethod = PasswordTransformationMethod.getInstance()
        setSelection(cursorPosition)
    }
}

some dynamic situation holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER); will not work so better use both like that

holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER);
holder.edit_pin.setTransformationMethod(PasswordTransformationMethod.getInstance());

Note : this is suitable for when you are using dynamic controls like using arrayaapter


Just an additional comment on the correct answer provided by @Rajkiran, you may want to add

etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

to the NORMAL input state so that the users wont be annoyed by the keyboard's auto-suggestion


Ok So after hours of trying finally implemented it. Below is the code ..

  buttons.get(2).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
       if(buttons.get(2).getText().toString().equalsIgnoreCase(getResources().getString(R.string.show))){
           editTexts.get(1).setInputType(InputType.TYPE_CLASS_TEXT);
           editTexts.get(1).setSelection(editTexts.get(1).getText().length());
           buttons.get(2).setText(getResources().getString(R.string.hide));
        }else{
           editTexts.get(1).setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
           //editTexts.get(1).setTransformationMethod(PasswordTransformationMethod.getInstance());
           editTexts.get(1).setSelection(editTexts.get(1).getText().length());
           buttons.get(2).setText(getResources().getString(R.string.show));
       }

    }
});

Explanations:- I have a button with default text as show. After onclick event on it checking if button's text is show. If it is show then changing the input type,adjusting the cursor position and setting new text as hide in it.

When it is hide... doing reverse i.e. hiding the password,adjusting the cursor and setting the text as show. And that's it. It is working like a charm.


Another simple example using ImageView to toggle visibility with less code, because of single InputType assign we need only equality operator:

EditText inputPassword = (EditText) findViewById(R.id.loginPassword);
ImageView inputPasswordShow = (ImageView) findViewById(R.id.imagePasswordShow);
inputPasswordShow.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         if(inputPassword.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
              inputPassword.setInputType( InputType.TYPE_CLASS_TEXT |
                                        InputType.TYPE_TEXT_VARIATION_PASSWORD);
         }else {
              inputPassword.setInputType( InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );
         }
         inputPassword.setSelection(inputPassword.getText().length());
    }
});

Replacing :

InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

With :

InputType.TYPE_CLASS_TEXT

Will give the same result but shorter word.


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

Method above didn't really work for me. Answer below works for 2.2 sdk.

password.setTransformationMethod(PasswordTransformationMethod.getInstance());

Set inputType for an EditText?


This worked for me:

mytext.setInputType(InputType.TYPE_CLASS_NUMBER);

Since the Support Library v24.2.0. you can achivie this very easy

What you need to do is just:

  1. Add the design library to your dependecies

    dependencies {
         compile "com.android.support:design:25.1.0"
    }
    
  2. Use TextInputEditText in conjunction with TextInputLayout

    <android.support.design.widget.TextInputLayout
        android:id="@+id/etPasswordLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true">
    
        <android.support.design.widget.TextInputEditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password_hint"
            android:inputType="textPassword"/>
    </android.support.design.widget.TextInputLayout>
    

passwordToggleEnabled attribute will make the password toggle appear

  1. In your root layout don't forget to add xmlns:app="http://schemas.android.com/apk/res-auto"

  2. You can customize your password toggle by using:

app:passwordToggleDrawable - Drawable to use as the password input visibility toggle icon.
app:passwordToggleTint - Icon to use for the password input visibility toggle.
app:passwordToggleTintMode - Blending mode used to apply the background tint.

More details in TextInputLayout documentation. enter image description here


This is the full onClick handler for the Image/Button to show/hide the password.

    new OnClickListener() {
        @Override
        public void onClick(View v) {
            // current ursor position
            int cursorPosition = edtPassword.getSelectionStart();

            // toggles the control variable
            isPassworsVisible = !isPassworsVisible;

            // sets the image toggler inside edit text
            passwordVisible.setImageDrawable(getResources().getDrawable(isPassworsVisible ? R.drawable.ic_eye_checked : R.drawable.ic_eye_unchecked));

            // apply input type
            edtPassword.setInputType(isPassworsVisible ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

            // returns cursor to position
            edtPassword.setSelection(cursorPosition);
        }
    };

Use this code to change password to text and vice versa. This code perfectly worked for me. Try this..

EditText paswrd=(EditText)view.findViewById(R.id.paswrd);

CheckBox showpass=(CheckBox)view.findViewById(R.id.showpass);
showpass.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
    if(((CheckBox)v).isChecked()){
        paswrd.setInputType(InputType.TYPE_CLASS_TEXT);

    }else{
        paswrd.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }

}
});

I would remove android:inputType="textPassword" from your layout. That is why it is switching back to password when the orientation changes. Because each time the orientation changes the view is being recreated.

As for the first problem try this:

String text = password.getText();
password.setText("");
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
password.setText(text);

basically emptying out the text before you change the input type and then add it back.


use this code to change password to text and vice versa

mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // checkbox status is changed from uncheck to checked.
                if (!isChecked) {
                        // hide password
                    mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                        // show password
                    mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });

for full sample code refer http://www.codeproject.com/Tips/518641/Show-hide-password-in-a-edit-text-view-password-ty


My search for a similar solution for Visual Studio / Xamarin lead me to this thread. Below is what worked for me with Xamarin. Note that this implementation retains the TYPE_TEXT_FLAG_NO_SUGGESTIONS flag when switching between modes.

EditText et = FindViewById<EditText>(Resource.Id.ET);

To show characters: et.InputType = Android.Text.InputTypes.TextVariationVisiblePassword | Android.Text.InputTypes.TextFlagNoSuggestions;

To hide characters: et.InputType = Android.Text.InputTypes.TextVariationPassword | Android.Text.InputTypes.ClassText;

To set position to end: int position = et.Text.Length; et.SetSelection(position, position);


For kotlin users:

password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD

After you setInputType for a password field, you will have problem with FONT
Here is my solution for show/hide password without font problem

protected void onCreate(Bundle savedInstanceState) {
    ...
    findViewById(R.id.button_show_hide_password).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isPasswordVisible(edtPassword)) {
                enableInputHiddenPassword(edtPassword);
            } else {
                enableInputVisiblePassword(edtPassword);
            }
            edtPassword.setSelection(edtPassword.getText().length());
        }
    });
}

final int INPUT_TYPE_VISIBLE_PASSWORD = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
final int INPUT_TYPE_HIDDEN_PASSWORD = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;

private boolean isPasswordVisible(EditText editText) {
    return editText.getInputType() == INPUT_TYPE_VISIBLE_PASSWORD;
}

private void enableInputVisiblePassword(EditText editText) {
    Typeface cache = editText.getTypeface();
    editText.setInputType(INPUT_TYPE_VISIBLE_PASSWORD);
    editText.setTypeface(cache);
}

private void enableInputHiddenPassword(EditText editText) {
    Typeface cache = editText.getTypeface();
    editText.setInputType(INPUT_TYPE_HIDDEN_PASSWORD);
    editText.setTypeface(cache);
}

Note: I use InputType.TYPE_TEXT_VARIATION_PASSWORD instead of InputType.TYPE_CLASS_TEXT or HideReturnsTransformationMethod because I want the keyboard display both text and number

DEMO


I change the input type on my checkbox, so on my OnCheckedChangeListener i do:

passwordEdit.setInputType(InputType.TYPE_CLASS_TEXT| (isChecked? InputType.TYPE_TEXT_VARIATION_PASSWORD|~InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD));

And it finally worked.

Seems like a boolean problem with TYPE_TEXT_VARIATION_VISIBLE_PASSWORD. Invert the flag and it should fix the problem.

In your case:

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|~InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

Use Transformation method:

To Hide:

editText.transformationMethod = PasswordTransformationMethod.getInstance()

To Visible:

editText.transformationMethod = SingleLineTransformationMethod.getInstance()

That's it.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to passwords

Your password does not satisfy the current policy requirements Laravel Password & Password_Confirmation Validation Default password of mysql in ubuntu server 16.04 mcrypt is deprecated, what is the alternative? What is the default root pasword for MySQL 5.7 MySQL user DB does not have password columns - Installing MySQL on OSX Changing an AIX password via script? Hide password with "•••••••" in a textField How to create a laravel hashed password Enter export password to generate a P12 certificate

Examples related to android-edittext

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Design Android EditText to show error message as described by google Change EditText hint color when using TextInputLayout How to change the floating label color of TextInputLayout The specified child already has a parent. You must call removeView() on the child's parent first (Android) Edittext change border color with shape.xml Changing EditText bottom line color with appcompat v7 Soft keyboard open and close listener in an activity in Android EditText underline below text property Custom designing EditText