好多APP登录页面为了查看自己输入密码是否正确都添加了明文查看的方法,也就是所谓的小眼睛,把小眼睛的代码分享给大家.
Activity:
//声明id:
private EditText etUserName;
private ImageView iv_eye;
//查找id
etPassword = findViewById(R.id.et_password);
iv_eye = findViewById(R.id.iv_eye);
//给小眼睛设置点击事件并调用切换明文密文方法
iv_eye.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showPwd(etPassword,iv_eye);
}
});
/**
* 切换明文密码
* @param etPassword需要切换显示的EditText数据
* @param iv_eye切换显示数据的图片
*isHidden 就是一个明文密文切换的开关
*/
protected boolean isHidden =true;
protected void showPwd(EditText etPassword, ImageView iv_eye){
if(isHidden){
//editText可见
etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
/**图标改变*/
iv_eye.setImageResource(R.drawable.ic_open_eye);
} else {
//editText不可见
etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
/**图标改变*/
iv_eye.setImageResource(R.drawable.ic_close_eye);
}
isHidden =!isHidden;
etPassword.postInvalidate();
//切换后将EditText光标置于末尾
CharSequence charSequence = etPassword.getText();
if (charSequence instanceof Spannable) {
Spannable spanText = (Spannable) charSequence;
Selection.setSelection(spanText, charSequence.length());
}
}
网友评论