I'm having a bit of trouble customizing the search icon in the SearchView. On my point of view, the icon can be changed in the Item attributes, right? Just check the code bellow..
Can someone tell me what I'm doing wrong?
This is the menu I'm using, with my custom search icon icn_lupa. But when I run the app, I always get the default search icon...
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_search"
android:title="@string/menu_search"
android:icon="@drawable/icn_lupa"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
</menu>
Thanks in advance.
Nice answer from @just_user
For my case, since I am using the appcompat v7 library for the SearchView + ActionBar, i modified his solution a bit to make it compatible to my project, it should work so as long as you did not modify anything when you added appcompat v7 as library
XML:
Java code:
Excuse for the very big icon (I have not resized the icon just yet), but it should work as it is.
After some research I found the solution here. The trick is that the icon is not in an
ImageView
but in theSpannable
object.Desperate solution using Kotlin
getAllChildren:
Hope it helps someone.
use the searchIcon xml tag
It looks like the actionViewClass overides the icon and it doesn't look like you can change it from this class.
You got two solutions:
There are three magnifying glass icons. two of them are shown when IconizedByDefault is true(one which is shown before pressing and one is shown in the "hint") and one is shown all the time when IconizedByDefault is false. all the fields are private so the way to get them is by their xml id. (most of the code is mentioned separately in other answers in this post already)
when IconizedByDefault is true change the icon in the hint (which is seen only after pressing the icon) by :
then do the same as in the android source code:
mSearchHintIcon was replaced with newSearchIconDrawable which is your new search icon. Then set the hint with
The other 2 icons are in an
ImageView
, which can be found by their Id. for the icon when searchview is closed (when iconizedByDefault is true) do:and for the one that always appears (if iconizedByDefault is false)