如何修改SearchView中searchHintIcon的颜色(非搜索状态颜色)
Got it, let's break down exactly how to tweak the color of that search hint icon—the one that shows up when your SearchView is collapsed and displaying the hint text, not the active search state. Here are a couple of reliable methods depending on whether you prefer XML or dynamic code changes:
Method 1: Using XML Styles (Static Color)
This is great if you want a fixed color for all instances of your SearchView.
First, create a custom style in your res/values/styles.xml file, inheriting from the AppCompat SearchView style (for better cross-version compatibility):
<style name="CustomSearchView" parent="Widget.AppCompat.SearchView"> <!-- Option 1: Tint the default hint icon directly --> <item name="searchHintIcon">@drawable/ic_search</item> <!-- Use the default search icon or your own --> <item name="tint">@color/your_target_color</item> <!-- Applies tint to the hint icon; note this affects other icons too --> <!-- Option 2: Use a pre-tinted drawable for precise control --> <!-- If you don't want to tint all icons, create a drawable with your desired color and reference it here --> <!-- <item name="searchHintIcon">@drawable/ic_search_tinted</item> --> </style>
Then apply this style to your SearchView in the layout:
<androidx.appcompat.widget.SearchView android:id="@+id/searchView" android:layout_width="match_parent" android:layout_height="wrap_content" style="@style/CustomSearchView" />
Method 2: Dynamic Color Change via Code
Perfect if you need to adjust the color at runtime (e.g., based on theme changes or user preferences).
Kotlin
val searchView = findViewById<SearchView>(R.id.searchView) // Locate the hint icon view (AppCompat SearchView uses this specific ID) val hintIcon = searchView.findViewById<ImageView>(androidx.appcompat.R.id.search_mag_icon) hintIcon?.setColorFilter( ContextCompat.getColor(this, R.color.your_target_color), PorterDuff.Mode.SRC_IN )
Java
SearchView searchView = findViewById(R.id.searchView); ImageView hintIcon = searchView.findViewById(androidx.appcompat.R.id.search_mag_icon); if (hintIcon != null) { hintIcon.setColorFilter( ContextCompat.getColor(this, R.color.your_target_color), PorterDuff.Mode.SRC_IN ); }
Quick Notes
- Stick with
androidx.appcompat.widget.SearchViewinstead of the nativeandroid.widget.SearchView—the hint icon ID differs between the two, and AppCompat offers smoother compatibility across Android versions. - If you must use the native SearchView, replace
androidx.appcompat.R.id.search_mag_iconwithandroid.R.id.search_button. - The
SRC_INPorterDuff mode ensures the color applies correctly without breaking the icon's transparency.
内容的提问来源于stack exchange,提问作者Ritu Suman Mohanty

