Search code examples
androidandroid-edittextgesturelistener

Edit text Password Toggle Android


I am trying to show user the typed password in edit text whose input type is text Password.

I implemented gesturelistener over the toggle icon like this-

public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (view.getId())
        {
            case R.id.ivPasswordToggle:

                switch ( motionEvent.getAction() ) {
                    case MotionEvent.ACTION_DOWN:
                        Toast.makeText(getContext(),"show",Toast.LENGTH_SHORT).show();
                        etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        break;
                    case MotionEvent.ACTION_UP:
                        etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                        Toast.makeText(getContext(),"hide",Toast.LENGTH_SHORT).show();
                        break;
                }
                break;
        }
        return true;
    }

i dont know what is wrong, any help will be appreciated.


Solution

  • (updated for AndroidX)

    Since the Support Library v24.2.0. you can achivie this very easy

    What you need to do is just:

    1. Add the design library to your dependecies

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

       <com.google.android.material.textfield.TextInputLayout
           xmlns:app="http://schemas.android.com/apk/res-auto"
           android:id="@+id/etPasswordLayout"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           app:passwordToggleEnabled="true">
      
           <android.support.design.widget.TextInputEditText
               android:id="@+id/etPassword"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:hint="@string/password_hint"
               android:inputType="textPassword"/>
       </com.google.android.material.textfield.TextInputLayout>
      

    passwordToggleEnabled attribute will make the password toggle appear

    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