EditText实现“眼睛”效果

EditText作为密码输入框时,常在右侧有一个眼睛的图片,以便于向用户展示密码,百度了一下多是通过自定义EditText实现的;
这里换个思路通过EditText的drawableRight实现。

1.准备个EditText
"@+id/et_pwd"
            android:paddingRight="10dp"
            android:drawableRight="@drawable/lol_icon_eye_close"
            // 默认关闭的眼睛,这里要先设置图片,以便于调整大小
            android:inputType="textPassword" 
            ...
/>
2.实现眼睛开闭
private boolean isHidePwd = true;// 输入框密码是否是隐藏的,默认为true
private void initView(){
...
et_pwd = (EditText) view.findViewById(R.id.et_pwd);
final Drawable[] drawables = et_pwd.getCompoundDrawables() ;
final int eyeWidth = drawables[2].getBounds().width() ;// 眼睛图标的宽度
final Drawable drawableEyeOpen = getResources().getDrawable(R.drawable.lol_icon_eye_open) ;
drawableEyeOpen.setBounds(drawables[2].getBounds());//这一步不能省略
et_pwd.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP){
            // getWidth,getHeight必须在这里处理
            float et_pwdMinX = v.getWidth() - eyeWidth - et_pwd.getPaddingRight() ;
            float et_pwdMaxX = v.getWidth() ;
            float et_pwdMinY = 0 ;
            float et_pwdMaxY = v.getHeight();
            float x = event.getX() ;
            float y = event.getY() ;
            if(x < et_pwdMaxX && x > et_pwdMinX && y > et_pwdMinY && y < et_pwdMaxY){
                // 点击了眼睛图标的位置
                isHidePwd = !isHidePwd ;
                if(isHidePwd){
                    et_pwd.setCompoundDrawables(drawables[0] ,
                        drawables[2] , 
                        drawables[3]);

        et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        }
                else {
                                        et_pwd.setCompoundDrawables(drawables[0] , 
                        drawableEyeOpen , 
                        drawables[3]);
                            et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        }
                    }
                }
                return false;
            }
        });
...
}
3.两个眼睛图片(放在drawable-hdpi中即可)

lol_icon_eye_close
lol_icon_eye_open

你可能感兴趣的:(android)