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

Anjali Patel picture Anjali Patel · Dec 28, 2016 · Viewed 13.5k times · Source

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

Answer

Charuක picture Charuක · Dec 28, 2016

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