直接在XML布局文件中引用布局,在Activity中进行焦点监听,有焦点且有输入时才显示删除图标。
public class EditTextWithDel extends EditText implements View.OnFocusChangeListener { private Drawable imgAble; private Context mContext; //点击区域大小 private int clickArea = 100; public EditTextWithDel(Context context) { this(context,null); } public EditTextWithDel(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; init(); } public EditTextWithDel(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; init(); } private void init() { setCursorColor(R.drawable.shape_cursor_color); imgAble = mContext.getResources().getDrawable(R.mipmap.icon_empty); addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { setDrawable(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); Android带删除按钮的编辑框 setOnFocusChangeListener(this); } //设置删除图片 public void setDrawable() { if (hasFocus()) { if (length() < 1) { setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } else { setCompoundDrawablesWithIntrinsicBounds(null, null, imgAble, null); } } else { setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } } // 处理删除事件 @Override public boolean onTouchEvent(MotionEvent event) { if (imgAble != null && event.getAction() == MotionEvent.ACTION_DOWN && hasFocus()) { int eventX = (int) event.getRawX(); int eventY = (int) event.getRawY(); Rect rect = new Rect(); int[] location = new int[2]; getLocationOnScreen(location); rect.right = location[0] + getWidth(); rect.left = rect.right - clickArea; rect.top = location[1]; rect.bottom = rect.top + getHeight(); if (rect.contains(eventX, eventY)) setText(""); } return super.onTouchEvent(event); } @Override protected void finalize() throws Throwable { super.finalize(); } @Override public void onFocusChange(View view, boolean b) { if (b) {//有焦点 setDrawable(); } else {//失去焦点 setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); ((EditTextWithDel) view).setTextColor(getResources().getColor(R.color.color_content_515559)); } } public int getClickArea() { return clickArea; } /** * 设置点击区域大小 * * @param clickArea */ public void setClickArea(int clickArea) { this.clickArea = clickArea; } /** * 设置光标颜色 * * @param res */ public void setCursorColor(int res) { try { Field f = TextView.class.getDeclaredField("mCursorDrawableRes"); f.setAccessible(true); f.set(this, res); } catch (Exception ignored) { } } }