今天看到一名大神的类似的项目中有写到这个,觉得很好用,就试着照着敲了一次
一、新建一个继承EditText的类
public class ClearEditText extends EditText {
...
}
二、新增一个初始化清除图标的方法
private void initView(Context context){
mClearIcon = getResources().getDrawable(R.drawable.edittext_clear_icon);
/*setBounds(x,y,width,height)
x:组件在容器X轴上的起点
y:组件在容器Y轴上的起点
width:组件的长度 height:组件的高度*/
mClearIcon.setBounds(0,0,mClearIcon.getMinimumWidth(),mClearIcon.getMinimumHeight());
/*文本监听事件*/
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
/*文本变化时*/
@Override
public void afterTextChanged(Editable editable) {
String text=getText().toString();
if (isFocused() && !text.isEmpty()){//处在焦点的文本不为空时
if (!mClearIconVisible){//清除图标不显示时
/*可以在上、下、左、右设置图标,如果不想在某个地方显示,则设置为null
* 注意:要添加的资源必须已经setBounds(Rect),即已经设置过初始位置、宽和高等信息
* */
setCompoundDrawables(null,null,mClearIcon,null);
mClearIconVisible=true;
}
}else {
setCompoundDrawables(null,null,null,null);
mClearIconVisible=false;
}
}
});
}
三、当点击图标时调用触屏事件
@Override
public boolean onTouchEvent(MotionEvent event) {
/*清除图标可见,当点击清除图标后松开时出发
* MotionEvent.ACTION_UP:当最后一个触点松开时被触发。
* MotionEvent.ACTION_CANCEL:触发事件结束*/
if (mClearIconVisible && mClearIcon!=null && event.getAction()==MotionEvent.ACTION_UP){
if (event.getX()> getWidth()-getPaddingRight()-mClearIcon.getIntrinsicWidth()){//判断清除图标的位置
setText("");
event.setAction(MotionEvent.ACTION_CANCEL);
}
}
return super.onTouchEvent(event);
}
关于Android MotionEvent可参考这个大神的Android MotionEvent详解
四、在构造函数中调用第二步写的方法
public ClearEditText(Context context){
super(context);
initView(context);
}
五、使用时可以直接在布局文件中调用
<com.example.woim.ui.ClearEditText
android:id="@+id/login_user_name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:background="@color/edit_text_color"
android:hint="@string/login_input_name"
android:padding="10dp" />