android自带小眼睛的编辑框,Android带清除按钮、密码可见小眼睛的输入框
时间: 2024-04-21 19:26:27 浏览: 9
是的,Android自带的EditText控件可以设置清除按钮和密码可见小眼睛,具体实现方法如下:
1.清除按钮
在EditText的布局文件中添加以下属性:
```
android:drawableRight="@drawable/ic_clear"
```
其中,ic_clear是清除按钮的图片资源。
同时,在EditText的Java代码中添加以下逻辑:
```
editText.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_RIGHT = 2;
if(event.getAction() == MotionEvent.ACTION_UP) {
if(event.getRawX() >= (editText.getRight() - editText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
editText.setText("");
return true;
}
}
return false;
}
});
```
这段代码的作用是监听EditText的触摸事件,当用户点击清除按钮时,清空EditText的内容。
2.密码可见小眼睛
在EditText的布局文件中添加以下属性:
```
android:drawableRight="@drawable/ic_visibility_off"
```
其中,ic_visibility_off是不可见状态的小眼睛图片资源。
同时,在EditText的Java代码中添加以下逻辑:
```
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
editText.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_RIGHT = 2;
if(event.getAction() == MotionEvent.ACTION_UP) {
if(event.getRawX() >= (editText.getRight() - editText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
if(editText.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_visibility, 0);
} else {
editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_visibility_off, 0);
}
return true;
}
}
return false;
}
});
```
这段代码的作用是监听EditText的触摸事件,当用户点击小眼睛按钮时,切换EditText的密码可见状态。同时,根据当前状态设置小眼睛按钮的图片资源。