How to hide and show password on button click in android?

18.6k views Asked by At

When button pressed want to visible the password otherwise it should be hidden or say dotted. I have Applied the following code but its not working. Any help would be appreciated.

 button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if(button.isPressed()) {
                upass.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                return true;
            }
            return true;
        }
   });
6

There are 6 answers

0
Charuක On BEST ANSWER

You have used OnTouchListener which gives you MotionEvent's. Use them! No need to check the button is pressed again as long as you are pressing it MotionEvent is there.

To visible a password field with with the password :inputType = TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

When the button is pressed MotionEvent.ACTION_UP So you can visible the text. When MotionEvent.ACTION_DOWN keep it as it was at the beginning.

 button.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {

            switch ( event.getAction() ) {

            case MotionEvent.ACTION_UP:
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            break;

            case MotionEvent.ACTION_DOWN:
            editText.setInputType(InputType.TYPE_CLASS_TEXT);
            break;

            }
            return true;
            }
            });
1
Anurag_Soni On

Enhanced password input view: toggle the visibility of the password. Hey! I decided to proceed with blogging after a delay to share more things about Android development. Today let's start with a simple one: password input field.

Enhanced password input. Usually, sign in or sign up UI forms have some input field for password. And Android SDK provides a simple way to have input field with hidden characters: EditText with inputType="textPassword". Very simple. However, if you need to type some long and complex password this could be a little bit tedious: it's quite easy to make a type and then you need to start password typing again.

Solution. So to make password input easier we can implement a simple but very effective solution: show an icon at the right edge of an input field, when you tap down the icon - typed password becomes visible, when you lift finger up - it's again shows only obscured characters. Simple, effective and secure!

There are at least three obvious possible ways to achieve that: compose default Android SDK views in a layout and put behaviour logic into a parent Fragment/Activity make a composed ViewGroup to encapsulate layout and behaviour logic make an EditText subclass that will manage custom drawable at the right side of the view

All that three ways will work good for you. Originally I've made with the 1st way for several reasons like: I don't like to create extra entities without a real necessity in it. Something like Occam's razor principal. :) I need to have it only in one place

Sure, if you need to have the same enhanced password views multiple times in different places choose 2nd or 3rd (preferable, cause view hierarchy is flat) options.

Implementation. So the simplest implementation of the enhanced password view with default Android SDK views only could looks like that:

  1. In a sign in XML layout (trivial and non topic related params like paddings are omitted):

    <RelativeLayout
    ...>
    
      <EditText
          android:id="@+id/fragment_login_password"
          android:inputType="textPassword"
      .../>
    
      <ImageView
          android:id="@+id/fragment_login_password_visibility"
          android:layout_alignRight="@+id/fragment_login_password"
          android:clickable="true"
          android:src="@drawable/ic_show_password"
      .../>
    </RelativeLayout> 
    
  2. In parent Fragment/Activity:

    2.1. For good UX let's add a text changed listener to show password visibility if there is some typed password value and to hide it for empty password view:

    mPasswordView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            mPasswordVisibilityView.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
        }
    });
    

    2.2. Set a touch listener for password visibility view to react on touches

    mPasswordVisibilityView.setOnTouchListener(mPasswordVisibleTouchListener);
    

Touch listener apply visible characters mode if finger is down inside the visibility view, and apply original password mode back when finger is up or leaves the visibility view. Also we take care about persisting of cursor position, so user can switch visibility mode at any time without loosing current input cursor position.

private View.OnTouchListener mPasswordVisibleTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final boolean isOutsideView = event.getX() < 0 ||
            event.getX() > v.getWidth() ||
            event.getY() < 0 ||
            event.getY() > v.getHeight();

    // change input type will reset cursor position, so we want to save it
    final int cursor = mPasswordView.getSelectionStart();

    if (isOutsideView || MotionEvent.ACTION_UP == event.getAction())
        mPasswordView.setInputType( InputType.TYPE_CLASS_TEXT | 
                                    InputType.TYPE_TEXT_VARIATION_PASSWORD);
    else
        mPasswordView.setInputType( InputType.TYPE_CLASS_TEXT | 
                                    InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

        mPasswordView.setSelection(cursor);
        return true;
    }
};

That's it! As I said it's very simple to implement, but it greatly improves UX!

3
Hetfieldan24 On

You shouldn't reinvent the wheel. Use it:

<android.support.design.widget.TextInputLayout
android:id="@+id/passwordLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true">

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

</android.support.design.widget.TextInputLayout>

Attribute app:passwordToggleEnabled show/hide the button you want. Note that you also must add this string to your app's build.gradle:

compile 'com.android.support:design:25.1.0'
0
Anjali Patel On

This Works:

   button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    upass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    return true;
                case MotionEvent.ACTION_UP:
                    upass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    return true;
            }
            return false;
        }
    });
0
Divyesh Patel On
showhide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                global.hideKeyboard();

                if(showhide.getText().equals("Hide"))
                {
                    showhide.setText("Show");
                    etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                else if(showhide.getText().equals("Show"))
                {
                    showhide.setText("Hide");
                    etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });
0
Syed Danish Haider On

In XML do like this and below is java code

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