1 package com.sixin.view;
2
3 import android.content.Context;
4 import android.graphics.Canvas;
5 import android.graphics.Color;
6 import android.graphics.Paint;
7 import android.graphics.Rect;
8 import android.graphics.drawable.Drawable;
9 import android.text.Editable;
10 import android.text.TextWatcher;
11 import android.util.AttributeSet;
12 import android.view.MotionEvent;
13 import android.widget.EditText;
14
15 import com.sixin.R;
16
17 /**
18 * 带删除图标的EditText
19 *
20 * @author shidongxue
21 *
22 */
23 public class EditTextWithDel extends EditText {
24 private Drawable imgInable;
25 private Context mContext;
26 private Paint mPaint;
27
28 public EditTextWithDel(Context context) {
29 super(context);
30 mContext = context;
31 init();
32 }
33
34 public EditTextWithDel(Context context, AttributeSet attrs, int defStyle) {
35 super(context, attrs, defStyle);
36 mContext = context;
37 init();
38 }
39
40 public EditTextWithDel(Context context, AttributeSet attrs) {
41 super(context, attrs);
42 mContext = context;
43 init();
44 }
45
46 private void init() {
47 mPaint = new Paint();
48 mPaint.setStyle(Paint.Style.STROKE);
49 mPaint.setColor(Color.GRAY);
50 imgInable = mContext.getResources().getDrawable(R.drawable.btn_del);
51 addTextChangedListener(new TextWatcher() {
52 @Override
53 public void onTextChanged(CharSequence s, int start, int before, int count) {
54 }
55
56 @Override
57 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
58 }
59
60 @Override
61 public void afterTextChanged(Editable s) {
62 setDrawable();
63 }
64 });
65 setDrawable();
66 }
67
68 // 设置删除图片
69 public void setDrawable() {
70 if (length() > 0 && isFocused()) {
71 setCompoundDrawablesWithIntrinsicBounds(null, null, imgInable, null);
72 } else {
73 setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
74 }
75 }
76
77 @Override
78 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
79 super.onFocusChanged(focused, direction, previouslyFocusedRect);
80 if (focused) {
81 setCursorVisible(true);
82 } else {
83 setCursorVisible(false);
84 }
85 setDrawable();
86 }
87
88 // 处理删除事件
89 @Override
90 public boolean onTouchEvent(MotionEvent event) {
91 if (imgInable != null && event.getAction() == MotionEvent.ACTION_UP) {
92 int eventX = (int) event.getRawX();
93 int eventY = (int) event.getRawY();
94 Rect rect = new Rect();
95 int r = getPaddingRight();
96 getGlobalVisibleRect(rect);
97 rect.left = rect.right - r - 60;
98 rect.right = rect.right - r;
99 if (rect.contains(eventX, eventY))
100 setText("");
101 }
102 return super.onTouchEvent(event);
103 }
104
105 @Override
106 protected void onDraw(Canvas canvas) {
107 super.onDraw(canvas);
108 }
109
110 @Override
111 protected void finalize() throws Throwable {
112 super.finalize();
113 }
114
115 }