我们常常在App的输入界面上看到:
当我们输入内容后,右面会出现这样一个小叉叉的图标,我们点击后会清空输入框中的内容!
实现起来其实也很简单:
为EditText设置addTextChangedListener,然后重写TextWatcher()里的抽象方法,这个用于监听输入框变化的;然后setCompoundDrawablesWithIntrinsicBounds设置小叉叉的图片;最后,重写onTouchEvent方法,如果点击区域是小叉叉图片的位置,清空文本!
实现代码如下:
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) { super(context, attrs); mContext = context; init(); } public EditTextWithDel(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; init(); } private void init() { imgInable = mContext.getResources().getDrawable(R.drawable.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, imgInable, null); } // 处理删除事件 @Override public boolean onTouchEvent(MotionEvent event) { if (imgInable != 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 - 100; if (rect.contains(eventX, eventY)) setText(""); } return super.onTouchEvent(event); } @Override protected void finalize() throws Throwable { super.finalize(); } }