Android学习笔记——自定义EditText增加清除功能

运算效果:

实现代码:

 1 import android.content.Context;
 2 import android.graphics.Rect;
 3 import android.graphics.drawable.Drawable;
 4 import android.text.Editable;
 5 import android.text.TextWatcher;
 6 import android.util.AttributeSet;
 7 import android.view.MotionEvent;
 8 import android.widget.EditText;
 9 
10 public class CustomEditText extends EditText {
11     private Drawable mRight;
12     private Rect mBounds;
13 
14     public CustomEditText(Context context) {
15         super(context);
16         init();
17     }
18 
19     public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
20         super(context, attrs, defStyle);
21         init();
22     }
23 
24     public CustomEditText(Context context, AttributeSet attrs) {
25         super(context, attrs);
26         init();
27     }
28 
29     private void init() {
30         setDrawable();
31         // 增加文本监听器
32         addTextChangedListener(new TextWatcher() {
33 
34             @Override
35             public void onTextChanged(CharSequence s, int start, int before,
36                     int count) {
37 
38             }
39 
40             @Override
41             public void beforeTextChanged(CharSequence s, int start, int count,
42                     int after) {
43 
44             }
45 
46             @Override
47             public void afterTextChanged(Editable s) {
48                 setDrawable();
49             }
50         });
51     }
52 
53     // 输入框右边的图标显示控制
54     private void setDrawable() {
55         if (length() == 0) {
56             setCompoundDrawables(null, null, null, null);
57         } else {
58             setCompoundDrawables(null, null, mRight, null);
59         }
60     }
61 
62     @Override
63     public void setCompoundDrawables(Drawable left, Drawable top,
64             Drawable right, Drawable bottom) {
65         if (mRight == null) {
66             this.mRight = right;
67         }
68         super.setCompoundDrawables(left, top, right, bottom);
69     }
70 
71     // 输入事件处理
72     @Override
73     public boolean onTouchEvent(MotionEvent event) {
74         if (mRight != null && event.getAction() == MotionEvent.ACTION_UP) {
75             this.mBounds = mRight.getBounds();
76             int eventX = (int) event.getX();
77             int width = mBounds.width();
78             int right = getRight();
79             if (eventX > (right - 2 * width)) {
80                 setText("");
81                 event.setAction(MotionEvent.ACTION_CANCEL);
82             }
83         }
84         return super.onTouchEvent(event);
85     }
86 
87     @Override
88     protected void finalize() throws Throwable {
89         super.finalize();
90         this.mRight = null;
91         this.mBounds = null;
92     }
93 
94 }

 

posted @ 2013-08-25 09:56  Agrimony  阅读(710)  评论(0)    收藏  举报