-3

I have an Edit text in android for a password field.The input type for the edit text is password.To, the right of the Edit text,I have a button which will show the password when the button is clicked.I have implemented the "Show Password" part using Motion Event in android.Below is the code which is working properly:

EditText passwordET;
Button showPassword;

passwordET = (EditText) findViewById(R.id.passwordET);
showPassword = (Button) findViewById(R.id.showpasswordBtn);

 showPassword.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        passwordET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        return true;

                    case MotionEvent.ACTION_UP:
                        passwordET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        return true;
                }
                return true;
            }
        });

The above code is working fine for the case when the user clicks on the Button, the password is shown and as the button touch event is removed, the text becomes Password field again. But,what I want is that if the button is clicked once,the edit text will show the password and the password will remain shown until the button is clicked again.So, when the button is clicked again, the edit text will change its state to password type again.Can anyone please let me know how to proceed?

Pranami
  • 27
  • 1
  • 10
  • easiest way check this ans: https://stackoverflow.com/a/39022642 – Jaydeep Devda Jun 05 '17 at 07:28
  • @JaydeepPatel Actually I want it with a button that will have the text written as "SHOW" which will show the password and when the password is shown,button state will change to "HIDE" and vice-versa. – Pranami Jun 05 '17 at 07:32
  • motion action is for scroll up down etc. https://developer.android.com/reference/android/view/MotionEvent.html – Jaydeep Devda Jun 05 '17 at 07:34

1 Answers1

0

Use below code:

Define one flag,

    boolean isPassWordShowing = false;

The click of ShowPassword Button:

showPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(isPassWordShowing)
            {
                passwordET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                isPassWordShowing = false;
            }
            else
            {
                passwordET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                isPassWordShowing = true;
            }


        }
    });
Ronak Thakkar
  • 2,515
  • 6
  • 31
  • 45