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

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;
});
}
}
<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 可正確朗讀。TextInputLayout + TextInputEditText + app:endIconMode="clear_text" 內建實現,零代碼達到同樣效果。<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>