Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實現帶有刪除按鈕的 EditText 範例

編輯:關於 Android 程式設計

在輸入框中加上刪除按鈕,是常見的互動設計。實作方式可以自訂一個繼承自 EditText 的類別,並在文字不為空時顯示刪除圖示。

自訂 EditTextWithDel

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();

            Rect rect = new Rect();
            getGlobalVisibleRect(rect);
            rect.left = rect.right - 70;

            if (rect.contains(eventX, eventY)) {
                setText("");
            }
        }

        return super.onTouchEvent(event);
    }
}

重點說明

setCompoundDrawablesWithIntrinsicBounds() 可用來設定控制項四周的圖示。此範例只設定右側刪除圖示。

在處理觸碰事件時,getRawX() 與 getRawY() 是相對於螢幕座標,而 getX() 與 getY() 是相對於父容器座標。若使用 getGlobalVisibleRect() 取得控制項在螢幕上的位置,就應搭配 getRawX() 與 getRawY() 判斷是否點擊到刪除圖示。

若改用 getLocalVisibleRect(),則可搭配 getX() 與 getY(),依座標系統調整即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved