萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android EditText 實現搜尋圖示與一鍵清空交互效果完整教學

效果預覽

輸入框右側顯示搜尋圖示 → 輸入文字後自動切換為清除圖示 → 點擊清除圖示一鍵清空並保持鍵盤狀態。

輸入前 輸入後

核心實現三步驟

  1. TextWatcher 監聽文字變化:動態切換右側 Compound Drawable。
  2. OnTouchListener 攔截觸摸事件:判斷點擊區域是否落在右側清除圖示上。
  3. 清空時保持輸入法狀態:暫時禁用輸入法再恢復,避免鍵盤閃爍。

完整代碼實作

public class SearchEditText extends AppCompatEditText {

    private Drawable mIconSearch;
    private Drawable mIconClear;
    private boolean mHasText = false;

    public SearchEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        // 載入圖示(建議使用 VectorDrawable 適配多密度)
        mIconSearch = ContextCompat.getDrawable(context, R.drawable.ic_search);
        mIconClear  = ContextCompat.getDrawable(context, R.drawable.ic_clear);
        setCompoundDrawablesWithIntrinsicBounds(null, null, mIconSearch, null);

        // 1. 文字變化監聽
        addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                boolean hasTextNow = !TextUtils.isEmpty(s);
                if (hasTextNow != mHasText) {
                    mHasText = hasTextNow;
                    setCompoundDrawablesWithIntrinsicBounds(
                            null, null, mHasText ? mIconClear : mIconSearch, null);
                }
            }
        });

        // 2. 觸摸事件攔截清除圖示點擊
        setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP && mHasText) {
                // 計算右側圖示區域(含 padding)
                int iconWidth = mIconClear.getIntrinsicWidth();
                int touchX = (int) event.getX();
                int rightBound = getWidth() - getPaddingRight();
                int leftBound = rightBound - iconWidth - getCompoundDrawablePadding();

                if (touchX >= leftBound && touchX <= rightBound) {
                    // 3. 清空並保持鍵盤
                    int inputType = getInputType();
                    setText("");
                    // 防止鍵盤彈出/收起閃爍
                    setInputType(InputType.TYPE_NULL);
                    onTouchEvent(event); // 傳遞事件給系統處理焦點
                    setInputType(inputType);
                    return true; // 消費事件
                }
            }
            return false;
        });
    }
}

XML 使用方式

<com.example.widget.SearchEditText
    android:id="@+id/et_search"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="搜尋..."
    android:padding="12dp"
    android:textSize="16sp"
    android:background="@drawable/bg_search_input" />

進階優化建議

  • 防抖動搜尋:在 afterTextChanged 中配合 Handler.postDelayed 或 RxJava debounce() 延遲發起網路請求。
  • 無障礙支援:為清除圖示設定 contentDescription,TalkBack 可正確朗讀。
  • Material Design 3:直接使用 TextInputLayout + TextInputEditText + app:endIconMode="clear_text" 內建實現,零代碼達到同樣效果。

Material 內建方案範例

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
    app:endIconMode="clear_text"
    app:startIconDrawable="@drawable/ic_search">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="搜尋..." />

</com.google.android.material.textfield.TextInputLayout>
copyright © 萬盛學電腦網 all rights reserved