先來看效果
這是一個帶有刪除按鈕的輸入文本框, 需要新建一個類繼承自EditText, 先把代碼貼出來, 然后在解釋:
public class EditTextWithDel extends EditText {
private final static String TAG = "EditTextWithDel";
private Drawable imgInable;
private Context mContext;
public EditTextWithDel(Context context) {
this(context, null, 0);
}
public EditTextWithDel(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EditTextWithDel(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
init();
}
private void init() {
imgInable = mContext.getResources().getDrawable(android.R.drawable.ic_delete);
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
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.d(TAG, "(" + eventX + ", " + eventY + ")");
Rect rect = new Rect();
getGlobalVisibleRect(rect);
rect.left = rect.right - 70;
Log.d(TAG, rect.toString());
if (rect.contains(eventX, eventY)) {
setText("");
}
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
首先看一下setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom)這個名字賊長的方法, 雖然名字很長, 其實這個方法用起來和簡單, 就是設置左上右下的圖片, 這個dome只需要設置右邊的就行了, 可以看一下全部設置的效果
接著就是還要監聽Touch, 這里要說一下getRawX()和getX()的區別, getRawX()或者getRawY()方法是以屏幕為參考, getX()和getY()方法是以容器為參考, 所以二者得到的值可能不一樣. 之后在利用getGlobalVisibleRect()方法得到視圖的位置, 存放到rect中, 這里是以屏幕左上角為起點的, 所以前面用的是getRaw方法.
當然也可以 使用getLocalVisibleRect方法, 這個方法是以View的左上角為起點的, 所以用這個方法的話, 就得使用getX()和getY()方法來或獲取觸摸點的x和y值了.