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

Android 輸入框的搜尋與清空效果實作

編輯:關於 Android 程式設計

本文要做的效果很常見:搜尋框在沒有內容時,右側顯示一個搜尋圖示;一旦使用者開始打字,圖示就換成「清除」按鈕,點它能把已輸入的文字一次清空。這是行動裝置搜尋框的標準互動模式。

效果預覽

一、綁定事件

private Drawable mIconSearchDefault; // 搜尋文本框默認圖標
private Drawable mIconSearchClear;   // 搜尋文本框清除文本內容圖標

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final Resources res = getResources();
    mIconSearchDefault = res.getDrawable(R.drawable.txt_search_default);
    mIconSearchClear = res.getDrawable(R.drawable.txt_search_clear);
    mSearchView = (EditText) findViewById(R.id.txtSearch);
    mSearchView.addTextChangedListener(tbxSearch_TextChanged);
    mSearchView.setOnTouchListener(txtSearch_OnTouch);
}

兩個監聽器各司其職:TextWatcher 負責「依內容切換圖示」,OnTouchListener 負責「偵測是否點到了清除圖示」。

二、觸摸事件

private OnTouchListener txtSearch_OnTouch = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_UP:
            int curX = (int) event.getX();
            if (curX > v.getWidth() - 38
                    && !TextUtils.isEmpty(mSearchView.getText())) {
                mSearchView.setText("");
                int cacheInputType = mSearchView.getInputType(); // backup the input type
                mSearchView.setInputType(InputType.TYPE_NULL);   // disable soft input
                mSearchView.onTouchEvent(event);                 // call native handler
                mSearchView.setInputType(cacheInputType);        // restore input type
                return true;                                     // consume touch event
            }
            break;
        }
        return false;
    }
};

這裡有兩個關鍵技巧值得拆解:

第一,用 X 座標判斷是否點在圖示上。因為 setCompoundDrawablesWithIntrinsicBounds 畫出來的圖示並不是獨立 View,無法個別掛監聽器,只能用「點擊位置 > 寬度 - 圖示區間」的方式模擬。這裡的 38 是圖示區塊的像素寬度,實作時可依實際圖示尺寸調整。

第二,清空後維持軟鍵盤狀態。這段「先把 inputType 設為 NULL、呼叫原生 onTouchEvent、再還原 inputType」的寫法,目的是讓清空動作不影響鍵盤的顯示狀態,避免使用者打完字按清除後鍵盤突然收起來。

三、監聽文字變化

// 監聽輸入
/**
 * 動態搜尋
 */
private TextWatcher tbxSearch_TextChanged = new TextWatcher() {
    // 緩存上一次文本框內是否為空
    private boolean isnull = true;

    @Override
    public void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(s)) {
            if (!isnull) {
                mSearchView.setCompoundDrawablesWithIntrinsicBounds(null,
                        null, mIconSearchDefault, null);
                isnull = true;
            }
        } else {
            if (isnull) {
                mSearchView.setCompoundDrawablesWithIntrinsicBounds(null,
                        null, mIconSearchClear, null);
                isnull = false;
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    /**
     * 隨著文本框內容改變動態改變列表內容
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
};

這裡有個容易被忽略的效能細節:用 isnull 這個旗標快取「上一次是否為空」,只在狀態真正翻轉時才呼叫 setCompoundDrawablesWithIntrinsicBounds。若無條件每次輸入都重設 Drawable,會造成不必要的重新配置與繪製,打字時就可能感覺到遲鈍。

程式碼要點回顧

  1. 為輸入框綁定觸摸事件,模擬點擊事件捕捉。透過監聽點擊區域判斷是否點中清除圖示,若在該區域且文本框不為空,則清空內容。
  2. 為輸入框綁定文字改變事件監聽,依內容有無動態切換圖示。
  3. 維持清空操作後的軟鍵盤狀態,讓互動不中斷。

最後提醒,onTouch 回傳 true 代表事件已被消費,此時若原本還掛著 OnClickListener,點擊事件將不會觸發。如果你的搜尋框同時需要處理 click,記得在清空分支之外把事件正確放行。

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