How to switch between hide and view password
Asked Answered
V

38

227

Is there a clever way to let the user switch between hide and view password in an android EditText? A number of PC based apps let the user do this.

Vandiver answered 10/9, 2010 at 15:11 Comment(0)
I
185

You can dynamically change the attributes of a TextView. If you would set the XML Atrribute android:password to true the view would show dots if you set it to false the text is shown.

With the method setTransformationMethod you should be able to change this attributes from code. (Disclaimer: I have not tested if the method still works after the view is displayed. If you encounter problems with that leave me a comment for me to know.)

The full sample code would be

yourTextView.setTransformationMethod(new PasswordTransformationMethod());

to hide the password. To show the password you could set one of the existing transformation methods or implement an empty TransformationMethod that does nothing with the input text.

yourTextView.setTransformationMethod(new DoNothingTransformation());
Illegalize answered 10/9, 2010 at 15:19 Comment(7)
To show the password, you don't need to make any new classes. Just call setTransformationMethod(null).Mortimer
@Illegalize , use of the following will give gud solution. setTransformationMethod(PasswordTransformationMethod.getInstance()); and setTransformationMethod(HideReturnsTransformationMethod.getInstance());Micronesia
@Illegalize but how to get show / hide keys in keyboard?Denten
when calling setTransformationMethod on an EditeText the onTextChanged callback of the EditText is being called...is it possible not this being happened?Mckinnie
Correct. The "setTransformationMethod() is the key. All you need is switch in your listener: etPassword.setTransformationMethod(null) / etPassword.setTransformationMethod(new PasswordTransformationMethod()). By default, set in your xml EditView "android:inputType="textPassword""Musket
The only way that actually worked for me programmatically, I needed my TextInputEditText to be numbers only and to also allow password visibility to be toggled on and off (when the person clicks the eye icon). These are the lines that helped me achieve that: textnputLayout.isPasswordVisibilityToggleEnabled = true textInputEditText.transformationMethod = PasswordTransformationMethod.getInstance() textInputEditText.inputType = InputType.TYPE_CLASS_NUMBER Pythia
Good, easy and simple solution, thank you but i don't know if you have noticed this or not but when you enable password mode, first character is getting visible for a little bit of time(while typing first character and also removing character until remains only first character)Protoplast
L
368

It is really easy to achieve since the Support Library v24.2.0.

What you need to do is just:

  1. Add the design library to your dependencies

     dependencies {
          implementation "com.google.android.material:material:1.9.0"
     }
    
  2. Use TextInputEditText in conjunction with TextInputLayout

    <com.google.android.material.textfield.TextInputLayout
         android:id="@+id/etPasswordLayout"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         app:passwordToggleEnabled="true"
         android:layout_marginTop="@dimen/_5sdp">
    
         <com.google.android.material.textfield.TextInputEditText
             android:id="@+id/etPassword"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:background="@drawable/bg_ed_box"
             android:hint="@string/enter_password"
             android:inputType="textPassword" />
     </com.google.android.material.textfield.TextInputLayout>
    

The passwordToggleEnabled attribute will do the job!

  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

Litha answered 18/8, 2016 at 15:53 Comment(6)
In version 25.1.0 I have a weird behavior: it shows the password toggle once but if you press it, it will disappear o_O'Gensmer
Yeah, there are also some quirks with android:text attribute on TextInputEditText. You can always raise an issue on Google Issues Tracker for AndroidLitha
is there any way to move the icon to the left side?Nudi
@Delta7 There are some ways and workarounds. Please, ask the question on SO, paste a link here and I will try to help you.Litha
Thanks. However, in my build the show/hide graphics are oddly reversed from your screenshot - it shows the crossed-out-eye when password is hidden - I guess someone decided buttons should show current state instead of action (or goal state).Messiaen
@JoshSutterfield agree. so if we want action button, we have to reverse it manually using app:passwordToggleDrawable (deprecated) or app:endIconDrawable then use custom drawable like <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ic_eye_close" android:state_checked="true"/> <item android:drawable="@drawable/ic_eye_open"/> </selector> I think google should fix this behavior. Good discussionHydrodynamic
I
185

You can dynamically change the attributes of a TextView. If you would set the XML Atrribute android:password to true the view would show dots if you set it to false the text is shown.

With the method setTransformationMethod you should be able to change this attributes from code. (Disclaimer: I have not tested if the method still works after the view is displayed. If you encounter problems with that leave me a comment for me to know.)

The full sample code would be

yourTextView.setTransformationMethod(new PasswordTransformationMethod());

to hide the password. To show the password you could set one of the existing transformation methods or implement an empty TransformationMethod that does nothing with the input text.

yourTextView.setTransformationMethod(new DoNothingTransformation());
Illegalize answered 10/9, 2010 at 15:19 Comment(7)
To show the password, you don't need to make any new classes. Just call setTransformationMethod(null).Mortimer
@Illegalize , use of the following will give gud solution. setTransformationMethod(PasswordTransformationMethod.getInstance()); and setTransformationMethod(HideReturnsTransformationMethod.getInstance());Micronesia
@Illegalize but how to get show / hide keys in keyboard?Denten
when calling setTransformationMethod on an EditeText the onTextChanged callback of the EditText is being called...is it possible not this being happened?Mckinnie
Correct. The "setTransformationMethod() is the key. All you need is switch in your listener: etPassword.setTransformationMethod(null) / etPassword.setTransformationMethod(new PasswordTransformationMethod()). By default, set in your xml EditView "android:inputType="textPassword""Musket
The only way that actually worked for me programmatically, I needed my TextInputEditText to be numbers only and to also allow password visibility to be toggled on and off (when the person clicks the eye icon). These are the lines that helped me achieve that: textnputLayout.isPasswordVisibilityToggleEnabled = true textInputEditText.transformationMethod = PasswordTransformationMethod.getInstance() textInputEditText.inputType = InputType.TYPE_CLASS_NUMBER Pythia
Good, easy and simple solution, thank you but i don't know if you have noticed this or not but when you enable password mode, first character is getting visible for a little bit of time(while typing first character and also removing character until remains only first character)Protoplast
E
126

To show the dots instead of the password set the PasswordTransformationMethod:

yourEditText.setTransformationMethod(new PasswordTransformationMethod());

of course you can set this by default in your edittext element in the xml layout with

android:password

To re-show the readable password, just pass null as transformation method:

yourEditText.setTransformationMethod(null);
Emlynne answered 8/3, 2011 at 10:51 Comment(5)
android:password is deprecated now, and you should use android:inputType instead.Regenaregency
You can also make your users happy by saving cursor position before setting transformation method and restoring after it. Use editText.getSelectionStart() and editText.getSelectionEnd() for saving cursor position and editText.setSelection(start, end) for restoring it.Maggoty
@Wilka: android:inputType does NOT let you switch back and forth between the two states at run-time. It only allows you to switch once and once you change it, you cannot change it back. And no, the setTransformationMethod is NOT deprecated.Usanis
@Emlynne but how to get show / hide keys in keyboard?Denten
@DroidWormNarendra you normally attach an event listener to a "eye image" between your password input, or inside your password input like explained here: #3554877 . Then in this event listener you can show/hide the password. AFAIK is not possible to have some show/hide keys in the keyboardEmlynne
T
103

To show:

editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

To hide:

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

After each of these the cursor is reset, so:

editText.setSelection(editText.length());
Traffic answered 20/11, 2014 at 22:6 Comment(4)
Tested on Android 4.3 & 5.0, works great! Docs make it look like this should work all the way down to API 3 to.Ensilage
@MattLogan but how to get show / hide keys in keyboard?Denten
This is the most straight forward answer here. Thanks. (weird it's not the accepted one)Turnover
This doesn't appear to work when changed at runtime. It also will not restore the user's last cursor position/selection if not at the end of the line.Sporocyst
N
36

You can use app:passwordToggleEnabled="true"

here is example given below

<android.support.design.widget.TextInputLayout
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true"
        android:textColorHint="@color/colorhint"
        android:textColor="@color/colortext">
Nannienanning answered 13/6, 2017 at 8:7 Comment(3)
Today it must be a preferred to use answerNodular
That increases the height of the view in my case. Is there any way to remove padding from toggle drawable.Dragonhead
This is deprecated in material components. Use app:endIconMode="password_toggle".Invincible
S
25

I had the same issue and it is very easy to implement.

All you have to do is wrap your EditText field in a (com.google.android.material.textfield.TextInputLayout) and in that add ( app:passwordToggleEnabled="true" ).

This will show the eye in the EditText field and when you click on it the password will appear and disappear when clicked again.

<com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColorHint="#B9B8B8"
                app:passwordToggleEnabled="true">

                <EditText
                    android:id="@+id/register_password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="24dp"
                    android:layout_marginRight="44dp"
                    android:backgroundTint="#BEBEBE"
                    android:hint="Password"
                    android:inputType="textPassword"
                    android:padding="16dp"
                    android:textSize="18sp" />
            </com.google.android.material.textfield.TextInputLayout>
Sneak answered 13/3, 2020 at 12:59 Comment(0)
C
14

Use checkbox and change the input type accordingly.

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    int start,end;
    Log.i("inside checkbox chnge",""+isChecked);
    if(!isChecked){
        start=passWordEditText.getSelectionStart();
        end=passWordEditText.getSelectionEnd();
        passWordEditText.setTransformationMethod(new PasswordTransformationMethod());;
        passWordEditText.setSelection(start,end);
    }else{
        start=passWordEditText.getSelectionStart();
        end=passWordEditText.getSelectionEnd();
        passWordEditText.setTransformationMethod(null);
        passWordEditText.setSelection(start,end);
    }
}
Cismontane answered 17/12, 2014 at 12:32 Comment(0)
I
11

At first this is the screen loaded with an image vector asset visibility enter image description here

on click it will change to this image visibility off enter image description here

code for above password switch(xml code)

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/laypass"
    android:layout_width="330dp"
    android:layout_height="50dp"
    android:layout_marginTop="24dp"
    app:layout_constraintEnd_toEndOf="@+id/editText3"
    app:layout_constraintStart_toStartOf="@+id/editText3"
    app:layout_constraintTop_toBottomOf="@+id/editText3">

    <EditText
        android:id="@+id/edit_password"
        style="@style/EditTextTheme"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/round"
        android:drawableLeft="@drawable/ic_password"
        android:drawablePadding="10dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        android:paddingLeft="10dp"
        android:paddingRight="15dp"
        android:textColor="@color/cyan92a6"
        android:textColorHint="@color/cyan92a6"
        android:textCursorDrawable="@null"
        android:textSize="18sp"
        />

    <ImageView
        android:id="@+id/show_pass_btn"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginEnd="8dp"
        android:alpha=".5"
        android:onClick="ShowHidePass"
        android:padding="5dp"
        android:src="@drawable/ic_visibility"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/laypass"
        app:layout_constraintTop_toTopOf="@+id/edit_password" /> 
 </androidx.constraintlayout.widget.ConstraintLayout>

Java code for button operation

public void ShowHidePass(View view) {

    if(view.getId()==R.id.show_pass_btn){
        if(edit_password.getTransformationMethod().equals(PasswordTransformationMethod.getInstance())){
            ((ImageView)(view)).setImageResource(R.drawable.ic_visibility_off);
            //Show Password
            edit_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
        else{
            ((ImageView)(view)).setImageResource(R.drawable.ic_visibility);
            //Hide Password
            edit_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }
}
Isle answered 8/2, 2020 at 21:24 Comment(0)
G
10
private boolean isPasswordVisible;

private TextInputEditText firstEditText;

...

firstEditText = findViewById(R.id.et_first);

...

    private void togglePassVisability() {
    if (isPasswordVisible) {
        String pass = firstEditText.getText().toString();
        firstEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        firstEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        firstEditText.setText(pass);
        firstEditText.setSelection(pass.length());           
    } else {
        String pass = firstEditText.getText().toString();
        firstEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        firstEditText.setInputType(InputType.TYPE_CLASS_TEXT);
        firstEditText.setText(pass);
        firstEditText.setSelection(pass.length());
    }
    isPasswordVisible= !isPasswordVisible;
}
Grapeshot answered 20/4, 2018 at 13:52 Comment(1)
Not need to set text again only call firstEditText.invalidate();Mcnulty
M
8

It's work for me.This will help you definitely

showpass.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(!isChecked){

                    // show password
                    password_login.setTransformationMethod(PasswordTransformationMethod.getInstance());

                    Log.i("checker", "true");
                }

                else{
                    Log.i("checker", "false");

                     // hide password
    password_login.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }

            }
        });
Micronesia answered 13/4, 2015 at 13:28 Comment(0)
S
6

I'm able to add the ShowPassword / HidePassword code with just a few lines, self-contained in a block:

protected void onCreate(Bundle savedInstanceState) {
    ...
    etPassword = (EditText)findViewById(R.id.password);
    etPassword.setTransformationMethod(new PasswordTransformationMethod()); // Hide password initially

    checkBoxShowPwd = (CheckBox)findViewById(R.id.checkBoxShowPwd);
    checkBoxShowPwd.setText(getString(R.string.label_show_password)); // Hide initially, but prompting "Show Password"
    checkBoxShowPwd.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
            if (isChecked) {
                etPassword.setTransformationMethod(null); // Show password when box checked
                checkBoxShowPwd.setText(getString(R.string.label_hide_password)); // Prompting "Hide Password"
            } else {
                etPassword.setTransformationMethod(new PasswordTransformationMethod()); // Hide password when box not checked
                checkBoxShowPwd.setText(getString(R.string.label_show_password)); // Prompting "Show Password"
            }
        }
    } );
    ...
Spoils answered 7/1, 2016 at 1:4 Comment(0)
I
5

I feel I want answer this question even there some good answers ,

according to documentation TransformationMethod do our mission

TransformationMethod

TextView uses TransformationMethods to do things like replacing the characters of passwords with dots, or keeping the newline characters from causing line breaks in single-line text fields.

Notice I use butter knife, but its the same if user check show password

@OnCheckedChanged(R.id.showpass)
    public void onChecked(boolean checked){
        if(checked){
            et_password.setTransformationMethod(null);
        }else {
            et_password.setTransformationMethod(new PasswordTransformationMethod());
            
        }
       // cursor reset his position so we need set position to the end of text
        et_password.setSelection(et_password.getText().length());
    }
Idolater answered 20/12, 2015 at 12:18 Comment(0)
C
5

In very simple form:

private fun updatePasswordVisibility(editText: AppCompatEditText) {
        if (editText.transformationMethod is PasswordTransformationMethod) {
            editText.transformationMethod = null
        } else {
            editText.transformationMethod = PasswordTransformationMethod()
        }
        editText.setSelection(editText.length())
    }

Hope it helps.

Chesna answered 25/7, 2019 at 13:24 Comment(0)
H
4
private int passwordNotVisible=1; 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
 showPassword = (ImageView) findViewById(R.id.show_password);
    showPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText paswword = (EditText) findViewById(R.id.Password);
            if (passwordNotVisible == 1) {
                paswword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                passwordNotVisible = 0;
            } else {

                paswword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                passwordNotVisible = 1;
            }


            paswword.setSelection(paswword.length());

        }
    });
}
Hellespont answered 22/12, 2016 at 7:42 Comment(0)
E
3

Try https://github.com/maksim88/PasswordEditText project at github. You dont even need to change your Java code using it. Just change

EditText

tag to

com.maksim88.passwordedittext.PasswordEditText

in your XML file.

Embrocation answered 10/2, 2016 at 2:10 Comment(1)
Do you have any idea how to use setError with this component, once the error is flagged the show/hide icon become invisibleConferee
A
3

You can SHOW/HIDE password using this below code:

XML CODE:

<EditText
        android:id="@+id/etPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="14dp"
        android:ems="10"
        android:inputType="textPassword" >
        <requestFocus />
    </EditText>
    <CheckBox
        android:id="@+id/cbShowPwd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/etPassword"
        android:layout_below="@+id/etPassword"
        android:text="@string/show_pwd" />

JAVA CODE:

EditText mEtPwd;
CheckBox mCbShowPwd;


mEtPwd = (EditText) findViewById(R.id.etPassword);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);

mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // checkbox status is changed from uncheck to checked.
        if (!isChecked) {
            // show password
            mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {
            // hide password
            mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
    }
});
Annikaanniken answered 12/3, 2017 at 11:58 Comment(0)
P
3

Try this:

First define a flag as global like this:

private boolean isShowPassword = false;

And set listener to handle tap on show and hide password button:

imgPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowPassword) {
                    etPassword.setTransformationMethod(new PasswordTransformationMethod());
                    imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_hide));
                    isShowPassword = false;
                }else{
                    etPassword.setTransformationMethod(null);
                    imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_show));
                    isShowPassword = true;
                }
            }
        });
Polaroid answered 10/7, 2019 at 10:20 Comment(0)
C
2

Did you try with setTransformationMethod? It's inherited from TextView and want a TransformationMethod as a parameter.

You can find more about TransformationMethods here.

It also has some cool features, like character replacing.

Crosspollinate answered 10/9, 2010 at 15:19 Comment(0)
T
2

show and hide password Edit_Text with check Box

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:inputType="textPassword"
        android:id="@+id/edtPass"
        android:textSize="20dp"
        android:hint="password"
        android:padding="20dp"
        android:background="#efeaea"
        android:layout_width="match_parent"
        android:layout_margin="20dp"
        android:layout_height="wrap_content" />

    <CheckBox
        android:background="#ff4"
        android:layout_centerInParent="true"
        android:textSize="25dp"
        android:text="show password"
        android:layout_below="@id/edtPass"
        android:id="@+id/showPassword"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:gravity="top|right"
        android:layout_height="wrap_content" />

</RelativeLayout>

java code

package com.example.root.sql2;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.Toolbar;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

public class password extends AppCompatActivity {


    EditText password;
    CheckBox show_hide_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hide);
        findViewById();
        show_hide_pass();



    }//end onCreate



    public void show_hide_pass(){
        show_hide_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!b){
                    // hide password
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());

                }else{
                    // show password
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });
    } // end show_hide_pass




    public void findViewById(){ //  find ids ui and
        password = (EditText) findViewById(R.id.edtPass);
        show_hide_password = (CheckBox) findViewById(R.id.showPassword);
    }//end findViewById



}// end class
Tripartition answered 5/11, 2018 at 23:3 Comment(0)
O
1

What I did was to

  1. Create an edit text view and a normal text view
  2. Make them overlap with each other by using constraint layout (just like Facebook app login screen)
  3. Attach an onClickListener to the normal text view so that it changes the input type of the edit text view accordingly (Visible / Non-visible)

You may check out this video for a more detailed steps and explanations https://youtu.be/md3eVaRzdIM

Hope it helps :)

Olivier answered 5/12, 2016 at 6:16 Comment(0)
S
1

Here is my solution without using TextInputEditText and Transformation method.

XML

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            style="@style/FormLabel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/username" />

        <EditText
            android:id="@+id/loginUsername"
            style="@style/EditTextStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_person_outline_black_24dp"
            android:drawableStart="@drawable/ic_person_outline_black_24dp"
            android:inputType="textEmailAddress"
            android:textColor="@color/black" />

        <TextView
            style="@style/FormLabel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="@string/password" />

        <EditText
            android:id="@+id/loginPassword"
            style="@style/EditTextStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableEnd="@drawable/ic_visibility_off_black_24dp"
            android:drawableLeft="@drawable/ic_lock_outline_black_24dp"
            android:drawableRight="@drawable/ic_visibility_off_black_24dp"
            android:drawableStart="@drawable/ic_lock_outline_black_24dp"
            android:inputType="textPassword"
            android:textColor="@color/black" />
    </LinearLayout>

Java Code

boolean VISIBLE_PASSWORD = false;  //declare as global variable befor onCreate() 
loginPassword = (EditText)findViewById(R.id.loginPassword);
loginPassword.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (event.getRawX() >= (loginPassword.getRight() - loginPassword.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    // your action here
                    //Helper.toast(LoginActivity.this, "Toggle visibility");
                    if (VISIBLE_PASSWORD) {
                        VISIBLE_PASSWORD = false;
                        loginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        loginPassword.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_outline_black_24dp, 0, R.drawable.ic_visibility_off_black_24dp, 0);
                    } else {
                        VISIBLE_PASSWORD = true;
                        loginPassword.setInputType(InputType.TYPE_CLASS_TEXT);
                        loginPassword.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_outline_black_24dp, 0, R.drawable.ic_visibility_black_24dp, 0);
                    }
                    return false;
                }
            }
            return false;
        }
    });
Surrey answered 2/7, 2017 at 6:40 Comment(0)
P
1

According to this source, if you have migrated your project to AndroidX, then you can replace

compile "com.android.support:design:24.2.0"

with

implementation "com.google.android.material:material:1.0.0"

Then all you have to do is to put the code below to your layout file:

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleEnabled="true"
    android:hint="@string/hint_text">

  <com.google.android.material.textfield.TextInputEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout>

More information about material TextInputLayout can be found here.

To this source, it is recommended to migrate to AndroidX from Android Support Library:

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

AndroidX is a major improvement to the original Android Support Library. Like the Support Library, AndroidX ships separately from the Android OS and provides backwards-compatibility across Android releases. AndroidX fully replaces the Support Library by providing feature parity and new libraries. In addition AndroidX includes the following features:

All packages in AndroidX live in a consistent namespace starting with the string androidx. The Support Library packages have been mapped into corresponding androidx.* packages. For a full mapping of all the old classes and build artifacts to the new ones, see the Package Refactoring page.

Unlike the Support Library, AndroidX packages are separately maintained and updated. The androidx packages use strict Semantic Versioning starting with version 1.0.0. You can update AndroidX libraries in your project independently.

All new Support Library development will occur in the AndroidX library. This includes maintenance of the original Support Library artifacts and introduction of new Jetpack components.

Princely answered 26/6, 2019 at 10:5 Comment(0)
S
1

A good solution. Set up a button, then use this code:

public void showPassword(View v)
{

    TextView showHideBtnText = (TextView) findViewById(R.id.textView1);

    if(showHideBtnText.getText().toString().equals("Show Password")){
        password.setTransformationMethod(null);
        showHideBtnText.setText("Hide");
    } else{
        password.setTransformationMethod(new PasswordTransformationMethod());
        showHideBtnText.setText("Show Password");
    }


}
Shigella answered 9/7, 2019 at 11:34 Comment(0)
R
1

1 - Make a selector file "show_password_selector.xml"

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pwd_hide"
          android:state_selected="true"/>
    <item android:drawable="@drawable/pwd_show"
          android:state_selected="false" />
 </selector>

2 - Aet "show_password_selector" file into imageview.

<ImageView
    android:id="@+id/iv_pwd"
    android:layout_width="@dimen/_35sdp"
    android:layout_height="@dimen/_25sdp"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="@dimen/_15sdp"
    android:src="@drawable/show_password_selector" />

3 - Put below code in java file.

iv_new_pwd.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (iv_new_pwd.isSelected()) {
            iv_new_pwd.setSelected(false);
            Log.d("mytag", "in case 1");
            edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT);
        } else {
            Log.d("mytag", "in case 1");
            iv_new_pwd.setSelected(true);
            edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }
});
Rusert answered 27/4, 2020 at 15:17 Comment(0)
V
1

You have to ask if the current text is already shown with dots, the function PasswordTransformationMethod.getInstance() allow you to do that.

This is my funtion in kotlin:

        fun hideAndShowPassword(editText: EditText, indicator: ImageView) {

        if (editText.transformationMethod == PasswordTransformationMethod.getInstance()) {
            editText.transformationMethod = HideReturnsTransformationMethod.getInstance()
            indicator.setImageDrawable(
                ContextCompat.getDrawable(
                    editText.context,
                    R.drawable.eye
                )
            )
            indicator.imageTintList =
                ContextCompat.getColorStateList(editText.context, R.color.colorTintIcons)
        } else {
            editText.transformationMethod = PasswordTransformationMethod.getInstance()
            indicator.setImageDrawable(
                ContextCompat.getDrawable(
                    editText.context,
                    R.drawable.eye_off
                )
            )
            indicator.imageTintList =
                ContextCompat.getColorStateList(editText.context, R.color.colorTintIcons)
        }

        editText.setSelection(editText.text.length)
    }
Victoir answered 19/8, 2020 at 22:43 Comment(1)
Welcome to Stack Overflow. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain how this answers the question and and how it improves on the many existing upvoted answers answers the question already has, so that it is useful to the OP as well as other users with similar issues.Advisory
C
1

Use the below code

    val hidePasswordMethod = PasswordTransformationMethod()
    showOrHidePasswordButton.setOnClickListener {
        passwordEditText.apply {
            transformationMethod =
                if (transformationMethod is PasswordTransformationMethod) 
                   null //shows password
               else 
                   hidePasswordMethod //hides password
        }
    }

and make sure you add this to your password edittext in layout

    android:inputType="textPassword"
Carreon answered 9/2, 2021 at 7:53 Comment(0)
F
1

It seems that input_layout.isPasswordVisibilityToggleEnabled = true is deprecated. And in my case I did it that way in Kotlin:

input_edit_text.inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD
input_layout.endIconMode = END_ICON_PASSWORD_TOGGLE

Where input_edit_text is com.google.android.material.textfield.TextInputEditText and input_layout is com.google.android.material.textfield.TextInputLayout. Of course you should import these asl well:

import android.text.InputType.TYPE_CLASS_TEXT
import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
import com.google.android.material.textfield.TextInputLayout.END_ICON_PASSWORD_TOGGLE

My may customize the icon with provided methods as these:

 input_layout.endIconDrawable = ...
 input_layout.setEndIconOnClickListener {  }
 input_layout.setEndIconOnLongClickListener(...)
Fullmouthed answered 25/5, 2021 at 11:58 Comment(0)
D
1

I used a OnClickListener() which is associated to the button that I want to use as toogle.

private EditText email_et, contraseña_et;
protected void onCreate(Bundle savedInstanceState) {
....
contraseña_et = (EditText) findViewById(R.id.contraseña_et);
....
vercontra_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int inputType = contraseña_et.getInputType();
            if (inputType == 129){
                contraseña_et.setInputType(1);
            } else {
                contraseña_et.setInputType(129);
            }
            contraseña_et.setSelection(contraseña_et.getText().length());
        }
    });

Reading docs, the int value seems to be different so I debugged to find the correct values, it's working awesome and is a little bit easier this way.

[Contraseña is password in spanish, btw]

Donnydonnybrook answered 29/5, 2021 at 16:49 Comment(0)
P
1
you can use this

private fun showPasswordSwitch(checked: Boolean) {

    registerBinding.registerActivityEditTextPassword.also {
        // Password hide-show
        it.inputType =
            if (checked) TEXT_PASSWORD_SHOW else TEXT_PASSWORD_HIDE
           
    }
}
const val TEXT_PASSWORD_SHOW = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

const val TEXT_PASSWORD_HIDE = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
Progressionist answered 31/10, 2022 at 18:3 Comment(0)
L
1

Updated code for TextInputLayout:

   <androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toTopOf="@+id/lg_forget_password"
    app:layout_constraintTop_toBottomOf="@+id/lg_name"
    app:cardElevation="@dimen/dp20"
    android:layout_marginStart="@dimen/dp20"
    app:cardCornerRadius="@dimen/dp10"
    android:layout_marginEnd="@dimen/dp20"
    android:id="@+id/textField">

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:backgroundTint="@android:color/transparent"
        app:boxStrokeWidth="0dp"
        app:boxStrokeWidthFocused="0dp"
        app:endIconMode="password_toggle"
        app:hintEnabled="false"
      >

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/lg_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/input_bg"
            android:drawableStart="@drawable/ic_baseline_lock_24"
            android:drawablePadding="@dimen/dp10"
            android:fontFamily="@font/roboto_flex"
            android:hint="@string/password"
            android:inputType="textPassword"
            android:padding="@dimen/dp15"
            android:singleLine="true" />

    </com.google.android.material.textfield.TextInputLayout>
</androidx.cardview.widget.CardView>

Result :

enter image description here

Leaves answered 26/12, 2022 at 9:13 Comment(0)
P
0

In XML do like this

    <LinearLayout
          android:layout_height="wrap_content"
          android:layout_width="fill_parent"
          android:orientation="vertical"
          >
          <RelativeLayout
              android:id="@+id/REFReLayTellFriend"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal"
              >
          <EditText
              android:id="@+id/etpass1"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:background="@android:color/transparent"
              android:bottomLeftRadius="10dp"
              android:bottomRightRadius="50dp"
              android:fontFamily="@font/frutiger"
              android:gravity="start"
              android:inputType="textPassword"
              android:hint="@string/regpass_pass1"
              android:padding="20dp"
              android:paddingBottom="10dp"
              android:textColor="#000000"
              android:textColorHint="#d3d3d3"
              android:textSize="14sp"
              android:topLeftRadius="10dp"
              android:topRightRadius="10dp"/>
              <ImageButton
                  android:id="@+id/imgshowhide1"
                  android:layout_width="40dp"
                  android:layout_height="20dp"
                  android:layout_marginTop="20dp"
                  android:layout_marginRight="10dp"
                  android:background="@drawable/showpass"
                  android:layout_alignRight="@+id/etpass1"/>
          </RelativeLayout>    

 boolean show=true;
 //on image click inside password do this
 if(show){
                imgshowhide2.setBackgroundResource(0);
                imgshowhide2.setBackgroundResource(R.drawable.hide);
                etpass2.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                etpass2.setSelection(etpass2.getText().length());

                show=false;
            }else{
                imgshowhide2.setBackgroundResource(0);
                imgshowhide2.setBackgroundResource(R.drawable.showpass);
                //etpass1.setInputType(InputType.TYPE_TEXT);
                etpass2.setInputType(InputType.TYPE_CLASS_TEXT |
                        InputType.TYPE_TEXT_VARIATION_PASSWORD);
                etpass2.setSelection(etpass2.getText().length());
                show=true;
            }
Prehistory answered 12/4, 2018 at 14:11 Comment(0)
R
0

My Kotlin extension . write once use everywhere

fun EditText.tooglePassWord() {
this.tag = !((this.tag ?: false) as Boolean)
this.inputType = if (this.tag as Boolean)
    InputType.TYPE_TEXT_VARIATION_PASSWORD
else
    (InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)

this.setSelection(this.length()) }

You can keep this method in any file and use it everywhere use it like this

ivShowPassword.click { etPassword.tooglePassWord() }

where ivShowPassword is clicked imageview (eye) and etPassword is Editext

Remodel answered 25/1, 2019 at 8:42 Comment(0)
R
0

Add this method:

fun EditText.revertTransformation() {
    transformationMethod = when(transformationMethod) {
        is PasswordTransformationMethod -> SingleLineTransformationMethod.getInstance()
        else -> PasswordTransformationMethod.getInstance()
    }
}

Call it will switch between input type state (you may change the Single-Line transformation to your favorite). Usage example:

editText.revertTransformation()
Raymundorayna answered 11/4, 2020 at 14:24 Comment(0)
A
0

Try this:

passwordEditText.setInputType(1);

Or

passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT);
Anderton answered 13/8, 2020 at 16:15 Comment(0)
M
0

If you want a simple solution you can use this extension of Android's EditText go to this link for more info: https://github.com/scottyab/showhidepasswordedittext

Add this to your build.gradle: implementation 'com.github.scottyab:showhidepasswordedittext:0.8'

Then change your EditText in your XML file.

From: <EditText

To: <com.scottyab.showhidepasswordedittext.ShowHidePasswordEditText

That's all.

Note: You can't see it while in XML Design, try to run it in your Emulator or Physical Device.

Maynard answered 10/2, 2021 at 11:41 Comment(0)
S
0

add inputtype to your edittext : android:inputType="textPassword" then change the inputType after getting the edit type :

val editTextPassword = dialogView.findViewById<EditText>(R.id.editTextPassword)`
`editTextPassword.inputType = InputType.TYPE_CLASS_TEXT // or InputType.TYPE_TEXT_VARIATION_PASSWORD
Sheets answered 25/11, 2023 at 10:43 Comment(0)
N
-1

Just create a checkbox in Xml file

and then simple write this function in java code

checkbox = findViewById(R.id.checkbox);
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){

                if (isChecked) {
                    password.setTransformationMethod(null);
                }
                else{
                    password.setTransformationMethod(new PasswordTransformationMethod());
                }
            }

        });
Noletta answered 2/4, 2021 at 9:16 Comment(0)
W
-2
if (inputPassword.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
 //password is visible
                inputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
else if(inputPassword.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
 //password is hidden
                inputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
Walling answered 5/6, 2017 at 13:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.