代码如下:
1 public class DeleteEditText extends EditText { 2 3 private Context mContext; 4 5 //删除图标 6 private Drawable drawableDelete; 7 8 public DeleteEditText(Context context) { 9 super(context); 10 mContext = context; 11 init(); 12 } 13 14 public DeleteEditText(Context context, AttributeSet attrs) { 15 super(context, attrs); 16 mContext = context; 17 init(); 18 } 19 20 public DeleteEditText(Context context, AttributeSet attrs, int defStyleAttr) { 21 super(context, attrs, defStyleAttr); 22 mContext = context; 23 init(); 24 } 25 26 27 private void init() { 28 drawableDelete = mContext.getResources().getDrawable(R.drawable.ic_inputbox_clear); 29 drawableDelete.setBounds(0, 0, drawableDelete.getIntrinsicWidth(), drawableDelete.getIntrinsicHeight()); 30 addTextChangedListener(new TextWatcher() { 31 @Override 32 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 33 34 } 35 36 @Override 37 public void onTextChanged(CharSequence s, int start, int before, int count) { 38 39 } 40 41 @Override 42 public void afterTextChanged(Editable s) { 43 setIcon(length() > 0); 44 } 45 }); 46 setIcon(false); 47 } 48 49 @Override 50 public boolean onTouchEvent(MotionEvent event) { 51 if (drawableDelete != null && event.getAction() == MotionEvent.ACTION_UP) { 52 //获取触摸点坐标 53 int eventX = (int) event.getRawX(); 54 int eventY = (int) event.getRawY(); 55 //获取整个EdtiText的可见区域 56 Rect rect = new Rect(); 57 getGlobalVisibleRect(rect); 58 //修改区域为图标区域 59 rect.left = rect.right - 80; 60 if (rect.contains(eventX, eventY)) { 61 //触摸点在图标区域,清空文本 62 setText(""); 63 } 64 } 65 return super.onTouchEvent(event); 66 } 67 68 //根据是否有内容来绘制图标 69 private void setIcon(boolean visible) { 70 Drawable right = visible ? drawableDelete : null; 71 setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); 72 } 73 }
时间: 2024-10-18 09:58:21