最近在项目中用到了带清除按钮的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() {
imgInable = mContext.getResources().getDrawable(R.mipmap.delete_gray);
imgAble = mContext.getResources().getDrawable(R.mipmap.delete);
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, imgInable, 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();
}
}
![这里写图片描述](https://img-blog.csdn.net/20170209195838190?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY29kZWx1Y2s=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)