Search code examples
javaandroidsearchview

How to change the style of SearchView?


I have to implement a SearchView in my application.

The XML declaration is as follows:

<SearchView
     android:id="@+id/searchView"
     style="@style/SearchViewStyle"
     android:layout_width="wrap_content"
     android:layout_height="20dp"
     android:layout_alignParentEnd="true"
     android:layout_marginTop="5dp"
     android:layout_marginBottom="5dp"
     app:layout_constraintBottom_toBottomOf="parent"
     app:layout_constraintEnd_toEndOf="parent"
     app:layout_constraintTop_toTopOf="parent" />

The style is:

<style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
 <item name="android:searchIcon">@drawable/ico_search</item>
 <item name="android:queryBackground">@android:color/transparent</item>

and finally in the activity:

SearchView mSearchView = findViewById(R.id.searchView);
mSearchView.setIconifiedByDefault(true);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setQueryHint("Search here");

I don't understand how to change the text color of the hint and the background of the "edittext" where I type the keywords used for the research.

What did I just try?

Add this line in the style.xml

<item name="android:textSize">18sp</item>
<item name="android:textColor">@color/white</item>

or add this in my activity

AutoCompleteTextView searchText = (AutoCompleteTextView) searchView.findViewById(R.id.abs__search_src_text);
searchText.setHintTextColor(getResources().getColor(color.black));
searchText.setTextColor(getResources().getColor(color.black));

Those solutions didn't work.


Solution

  • You can style your SearchView like this:

    <style name="Theme.MyTheme" parent="Theme.AppCompat">
       <item name="searchViewStyle">@style/MySearchViewStyle</item>
    </style>
    <style name="MySearchViewStyle" parent="Widget.AppCompat.SearchView">
       <!-- Background for the search query section (e.g. EditText) -->
       <item name="queryBackground">...</item>
       <!-- Background for the actions section (e.g. voice, submit) -->
       <item name="submitBackground">...</item>
       <!-- Close button icon -->
       <item name="closeIcon">...</item>
       <!-- Search button icon -->
       <item name="searchIcon">...</item>
       <!-- Go/commit button icon -->
       <item name="goIcon">...</item>
       <!-- Voice search button icon -->
       <item name="voiceIcon">...</item>
       <!-- Commit icon shown in the query suggestion row -->
       <item name="commitIcon">...</item>
       <!-- Layout for query suggestion rows -->
       <item name="suggestionRowLayout">...</item>
    </style>
    

    Here is details information https://philio.me/styling-the-searchview-with-appcompat-v21/