Skip to main content

Android : Password Show Hide EditText

Please follow below steps to accomplish the show/hide functionality on EditText

Add EditText to your text file

<EditText        android:id="@+id/password"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:inputType="textPassword"        android:ems="10"        android:drawableRight="@drawable/eye"        android:layout_centerHorizontal="true"        />

Add OnTouchListener for EditText

editText = findViewById(R.id.password);editText.setOnTouchListener(new View.OnTouchListener() {
    @Override    public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_LEFT = 0;        final int DRAWABLE_TOP = 1;        final int DRAWABLE_RIGHT = 2;        final int DRAWABLE_BOTTOM = 3;
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            if(event.getRawX() >= (editText.getRight() - editText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                if(editText.getTransformationMethod().equals(HideReturnsTransformationMethod.getInstance())){
                    editText.setTransformationMethod(PasswordTransformationMethod.getInstance());                }else{
                    editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());                }
                return true;            }
        }
        return false;    }
});

Comments