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

24

226

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?

Bourque answered 27/3, 2012 at 15:26 Comment(2)
How to set email type for edit text mailEdt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS); not seems to work.Cavalierly
Use mailEdt.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);. Works for me.Bourque
B
416

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
Bourque answered 27/3, 2012 at 16:14 Comment(7)
as noted for correct answer - instead of changing selection you can use InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORDArris
i don't understand why in the world android chooses to move the cursor, it just makes developers life much more difficult.Martian
+1 for here is best answerHeyer
How to write | in layout file when using data binding.I tried this: android:inputType='@{oneField.IsMasked==true ? (InputType.TYPE_CLASS_TEXT | inputType.TYPE_TEXT_VARIATION_PASSWORD) : InputType.TYPE_CLASS_TEXT }' It doesn't compileHereditable
@Vlado It works for me using Data Binding as well. I have updated my answer.Bourque
If the user is editing the middle of the password field, this will constantly put the cursor at the end. I'd recommend using editText.getSelectionStart() and editText.getSelectionEnd() with setSelection(start, end) to avoid this issue.Chauffeur
People shouldn't even be looking further down. This is the best answer and would suggest that you make @JM Lord's suggested change.Polemist
R
72

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

Retortion answered 1/10, 2013 at 6:29 Comment(8)
HideReturnsTransformationMethod.getInstance() showed password, and PasswordTransformationMethod.getInstance() hide password ... implementation is correct but the comments are reversedSargassum
This is the best answer, to complete it, just move the cursor to the last character with: txtpassword.setSelection(txtpassword.getText().length());Crucify
For a moment it seems not working due to point highlighted by EL-conte De-monte TereBentikh. Josh suggestion is also helpful. This is best answer.Scarletscarlett
Simple and best thnksPhosphor
You are THE professor my friend! With this solution you are not facing issues with font after changing back to Password mode (secure text).Quesenberry
This answer better than accepted answer setInputType which cause hint added extra spacing between characters.Mainmast
But still, you should define android:inputType="textPassword" as default in xml or else even android:maxLines="1" will not works to make it single line.Mainmast
This way is better than setInputType, because it preserves the keyboard layout (see the pictures)Sear
E
18
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?

Electrophilic answered 3/8, 2012 at 7:44 Comment(0)
D
16

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.

Darg answered 9/6, 2015 at 15:6 Comment(0)
R
13
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());       
                }
            }
        });
Romalda answered 9/12, 2015 at 6:24 Comment(0)
M
7

For kotlin users:

password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
Micrometer answered 14/8, 2018 at 12:17 Comment(1)
And this will only hide password symbols?Deutschland
T
6

This worked for me:

mytext.setInputType(InputType.TYPE_CLASS_NUMBER);
Timikatiming answered 8/11, 2012 at 15:44 Comment(1)
Please read the question first. I want to toggle between password field and textfield. This will give me numeric textfield.Bourque
T
5

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);
    }

}
});
Talley answered 18/2, 2015 at 16:19 Comment(1)
How is it different from the accepted answer? Please read the question and the answer carefully before spamming.Bourque
C
5

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.

Currajong answered 8/11, 2017 at 12:27 Comment(0)
L
3

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);
        }
    };
Lottie answered 22/1, 2015 at 14:23 Comment(1)
Thanks for edtPassword.getSelectionStart().Deutschland
M
3

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.

Monstrous answered 22/8, 2016 at 10:0 Comment(0)
H
3

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

Herta answered 15/12, 2016 at 14:40 Comment(0)
E
3

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

Eparch answered 5/9, 2018 at 6:21 Comment(0)
S
3

Use Transformation method:

To Hide:

editText.transformationMethod = PasswordTransformationMethod.getInstance()

To Visible:

editText.transformationMethod = SingleLineTransformationMethod.getInstance()

That's it.

Suppression answered 4/5, 2020 at 19:39 Comment(0)
L
2

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.

Lamberto answered 27/3, 2012 at 15:36 Comment(1)
Not working. I even tried putting password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); immediately after initialization, but alas!Bourque
S
2

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

Stelliform answered 10/7, 2014 at 9:49 Comment(0)
S
2

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);

Swore answered 2/9, 2016 at 1:18 Comment(2)
how to use this code 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 ); } for Visual Studio/Xamarin..?Bearskin
i mean how to get the inputtype of the edittext in if() condition..?Bearskin
O
2

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);
Ofilia answered 11/1, 2017 at 20:2 Comment(0)
D
1

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

Dyandyana answered 9/2, 2015 at 12:38 Comment(0)
N
1

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.

Nanny answered 10/4, 2015 at 10:2 Comment(2)
@PKR check the implementation buddy, which in this case is ready to use! :)Nanny
@Nanny do u have any idea that how to write the if condition in Xamarin/visual Studio..?Bearskin
E
0

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]--;
            }

        }
    });
Empoison answered 29/6, 2016 at 11:56 Comment(0)
D
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)
    }
}
Deutschland answered 20/9, 2018 at 7:54 Comment(0)
M
0

etPost.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);

Mn answered 24/6, 2021 at 8:0 Comment(1)
Welcome to Stack Overflow. Code without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See How to Answer.Coquillage
I
0

To change your password to visible text, use this

profileSignupDialogBinding.signupDialogPassword.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

To change it back to hidden text, use this

profileSignupDialogBinding.signupDialogPassword.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
profileSignupDialogBinding.signupDialogPassword.transformationMethod = PasswordTransformationMethod.getInstance()

This should work well.

Inurbane answered 27/12, 2022 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.