经常见到EditText的后面带着一个小的“x”,可以把EditText输入的内容清空,这是一个即使用又简单的功能,我们一起来重写一下EditText来实现这个功能:
public class EdittextWithDel extends EditText {
private final static String TAG = "EditTextWithDel";
private Drawable imgInable;
private Drawable imgAble;
private Context mContext;
public EdittextWithDel(Context context) {
super(context);
mContext = context;
init();
}
public EdittextWithDel(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
public EdittextWithDel(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
private void init() {
imgAble = mContext.getResources().getDrawable(
R.mipmap.icon_delete_gray);
addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
setDrawable();
}
});
setDrawable();
}
// 设置删除图片
private void setDrawable() {
if (length() < 1) {
setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
} else {
setCompoundDrawablesWithIntrinsicBounds(null, null, imgAble, null);
}
}
// 处理删除事件
@Override
public boolean onTouchEvent(MotionEvent event) {
if (imgAble != null && event.getAction() == MotionEvent.ACTION_UP) {
int eventX = (int) event.getRawX();
int eventY = (int) event.getRawY();
Log.e(TAG, "eventX = " + eventX + "; eventY = " + eventY);
Rect rect = new Rect();
getGlobalVisibleRect(rect);
rect.left = rect.right - 50;
if (rect.contains(eventX, eventY))
setText("");
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
当然为了美观,我们也为EditText的外围加一个框:
<?xml version="1.0" encoding="utf-8"?><!--定义一个带圆角,白色背景,绿色边框的矩形-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--填充颜色-->
<solid android:color="#F0F0F0" />
<!--描边-->
<stroke
android:width="1dp"
android:color="#DEDEDE" />
</shape>
然后给上那个小“x”的图片:
大功告成。