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

6

5

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;
        }
   });
Dibranchiate answered 28/12, 2016 at 12:20 Comment(2)
#9893117Liborio
refer How to switch between hide and view passwordPazpaza
B
8

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;
            }
            });
Bowdlerize answered 28/12, 2016 at 12:23 Comment(0)
T
8
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());
                }
            }
        });
Tasiatasiana answered 28/12, 2016 at 12:22 Comment(0)
B
8

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;
            }
            });
Bowdlerize answered 28/12, 2016 at 12:23 Comment(0)
N
2

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'
Nitty answered 28/12, 2016 at 13:51 Comment(3)
Its not working. Giving error - Error:(123) No resource identifier found for attribute 'passwordToggleEnabled' in package 'android'. @NittyDibranchiate
It looks like you used android:passwordToggleEnabled="true"> instead of app:passwordToggleEnabled="true". Please, post your xml file. Do you put xmlns:app="schemas.android.com/apk/res-auto"; in your root layout in this file?Nitty
@Nitty worked like a charm. this must be the accepted answerGavelkind
K
1

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!

Kos answered 28/12, 2016 at 12:42 Comment(1)
Thankyou so much for the very well explanation. But unfortunately View.OnTouchListener mPasswordVisibleTouchListener.... this code is not working. @Anurag_SystematixDibranchiate
O
1

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;
            }
Oldham answered 12/4, 2018 at 14:13 Comment(0)
D
0

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;
        }
    });
Dibranchiate answered 29/12, 2016 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.