一、首先來看看效果
這是一個帶有刪除按鈕的輸入文字框, 需要建立一個類繼承自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值了.
總結
以上就是這篇文章的全部內容了,希望本文的內容對各位Android開發人員們能有所協助,如果有疑問大家可以留言交流。