The default SearchView when expanded in the ActionBar looks like this image :
I want to customize expanded SearchView similar to this image :
I am pretty new in Android Development. I would highly appreciate if someone can help me.
SearchView for Androidx Package is composed by an EditText and some AppCompatImageView like the close icon and the search icon
To customize it you must access these views that I have talked about
for exmaple to change the background like the image you showed you need to create a shape like belew :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#02B15D" />
<corners android:radius="15dp" />
<stroke
android:width="2dp"
android:color="#1A40FF" />
</shape>
this is how it's look the shape :
The shape above you must add it in the background of the EditText
To get this EditText is simple just use this in you onCreateOptionMenu
:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
EditText editText = (searchView.findViewById(androidx.appcompat.R.id.search_src_text)); // get the EditText from it
editText.setBackgroundResource(R.drawable.round_search); // set the background to searchView
// you can do more with the editText like textColor hint color .....
return super.onCreateOptionsMenu(menu);
}
For customize the search icon use this
AppCompatImageView searchIcon = searchView.findViewById(androidx.appcompat.R.id.search_mag_icon);
For the search button shown the the toolBar use this :
AppCompatImageView search_button = searchView.findViewById(androidx.appcompat.R.id.search_button);
And finaly for the close button use this :
AppCompatImageView search_close_btn = searchView.findViewById(androidx.appcompat.R.id.search_close_btn);
And this how the result looks like :
To make the search icon visible at the left inside the SearchView you can add an icon to the EditText with this method :
editText.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_menu_search,0,0,0);
If you use :
AppCompatImageView searchIcon = searchView.findViewById(androidx.appcompat.R.id.search_mag_icon); searchIcon.setImageResource(android.R.drawable.ic_menu_search);
you must add searchView.setIconifiedByDefault(false);
but the icon becom visible outsid the shape please see the image below :
So if you want the icon inside the shape use the first method