In this blog, we will learn on how to change the text colors and icons of the searchview in action bar.
We all inflate some menu in all our activities to make our app user interactive.
While working in the same manner, I used the search item but then after sometime i needed to change the same to an expanded search view along with all the other action icons present.
One approach was to make the toolbar and inflate in every activity, but that would be very cumbersome.
So i decided to look up and experiment with the search view that i created in”onCreateOptionsMenu” method.
And finally i got success.
All you need to do is to override the default resources associated with the search view which in turn are picked as per the styles.xml file or default theme applied in your application.
Yes , of course you can create the style attribute for search view and apply it to all the search views you want to.
But i did it with java.
STEPS TO FOLLOW :
- Expand the search view by setting iconified and iconifiedByDefault flags to false.
- Find views inside the search view and set the colors as per your wish.
- Find views of the icons you wish to change and replace them with your icons.
And it’s done.
Lets have a look at the code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/* Getting a referrence to the search view */ MenuItem searchItem = menu.findItem(R.id.search); SearchView my_search_view = (SearchView) MenuItemCompat.getActionView(searchItem); /*Expanding the search view */ my_search_view.setIconified(false); my_search_view.setIconifiedByDefault(false); /* Code for changing the textcolor and hint color for the search view */ SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete)my_search_view.findViewById(android.support.v7.appcompat.R.id.search_src_text); searchAutoComplete.setHintTextColor(#FFFFFF); searchAutoComplete.setTextColor(#FFFFFF); /*Code for changing the search icon */ ImageView searchIcon = (ImageView)my_search_view.findViewById(android.support.v7.appcompat.R.id.search_mag_icon); searchIcon.setImageResource(R.drawable.my_search_icon); /*Code for changing the voice search icon */ ImageView voiceIcon = (ImageView)my_search_view.findViewById(android.support.v7.appcompat.R.id.search_voice_btn); voiceIcon.setImageResource(R.drawable.my_voice_search_icon); |
That’s all, check it out.
Keep coding, Keep sharing : )