EditText一键清空

  当我们使用EditText时,有时候需要删除一整行,但EditText只允许一个个删除,这就比较烦恼了。其实最好的办法就是重写EditText,先看效果图:

  完整源码:https://github.com/JustDoI/EditTextModel-master

10.png

  重写效果如下,只有当EditText内容不为空且获得焦点时才会出现删除按钮,点击删除按钮删除所有内容。废话不多说,主要代码如下:

  private void setClearIconVisible(boolean visible) {
      Drawable temp = visible ? _right : null;
      Drawable\[\] drawables = getCompoundDrawables();
      setCompoundDrawables(drawables\[0\], drawables\[1\], temp, drawables\[3\]);
 }
 
 
  @Override
  public void onFocusChange(View v, boolean hasFocus) {
      setClearIconVisible(hasFocus && !TextUtils.isEmpty(getText()));
      if (_f != null) {
          _f.onFocusChange(v, hasFocus);
       }
 }
 
  @Override
  public boolean onTouch(View v, MotionEvent event) {
      if (getCompoundDrawables()\[2\] != null) {
           boolean tapped = event.getX() > (getWidth() - getPaddingRight() - _right.getIntrinsicWidth());
            if (tapped) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                   setText("");
                      }
            return true;
            }
        }
           if (_t != null) {
                return _t.onTouch(v, event);
                }
            return false;
 }

 API中可以为EditText设置上下左右的图标。代码简单,相信大家都能看懂,在此就不过多解释。