首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android SearchView 修改輸入文字與 Hint 字體大小顏色

     編輯:程式設計疑難解答

核心代碼


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)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved