问题描述:Android密码可见性切换按钮未显示。
解决方法:
EditText passwordEditText = findViewById(R.id.passwordEditText);
ImageView passwordVisibilityToggle = findViewById(R.id.passwordVisibilityToggle);
passwordVisibilityToggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (passwordEditText.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
passwordVisibilityToggle.setImageResource(R.drawable.ic_visibility_off);
} else {
passwordEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
passwordVisibilityToggle.setImageResource(R.drawable.ic_visibility);
}
// 将光标移动到最后一位
passwordEditText.setSelection(passwordEditText.getText().length());
}
});
在 res/drawable 文件夹中添加 ic_visibility.xml
文件,内容如下:
ic_visibility_on.xml
和 ic_visibility_off.xml
文件,分别用于显示密码可见性开和关的图标。ic_visibility_on.xml 内容如下:
ic_visibility_off.xml 内容如下: