核心代碼
SearchView searchView = findViewById(R.id.search);
if (searchView == null) return;
// 獲取輸入框 TextView (ID 為 search_src_text)
int id = searchView.getContext().getResources()
.getIdentifier("android:id/search_src_text", null, null);
TextView textView = searchView.findViewById(id);
textView.setTextColor(Color.RED); // 輸入文字顏色
textView.setTextSize(20); // 字體大小 (sp)
textView.setHintTextColor(Color.BLUE); // Hint 顏色
// textView.setHint("搜索..."); // 修改 Hint 文字
進階:搜索圖標、提交圖標、背景
// 搜索圖標
ImageView searchIcon = searchView.findViewById(
searchView.getContext().getResources()
.getIdentifier("android:id/search_mag_icon", null, null));
searchIcon.setImageResource(R.drawable.ic_custom_search);
// 提交圖標 (鍵盤動作按鈕)
ImageView goIcon = searchView.findViewById(
searchView.getContext().getResources()
.getIdentifier("android:id/search_go_btn", null, null));
goIcon.setImageResource(R.drawable.ic_custom_go);
// 背景
View plate = searchView.findViewById(
searchView.getContext().getResources()
.getIdentifier("android:id/search_plate", null, null));
plate.setBackgroundResource(R.drawable.bg_search_view);
注意
- 內部 ID (`search_src_text` 等) 屬於 Android 內部實現,**不同版本/廠商 ROM 可能不同**,建議運行時 `try-catch` 防崩潰。
- 更穩健方案:自定義佈局 `app:searchViewLayout` 或用 `MaterialSearchView` 等第三方庫。
- API 29+ 可用 `searchView.getQueryTextView()` 直接獲取 (但非公開 API)。