In Android, we can easily create the Searchview in ActionBar / Toolbar, which provides the option to perform the search, particularly when a list of data is present. Android search view in actionbar In this post we will see how to do that.
In sort, Searchview is a widget that provides a user interface for the user to enter a search query and submit a request to a search provider. As a result, it shows a list of query suggestions or results, if available, and allows the user to pick a suggestion or result to launch into.
More at Developer site
To inflate the search view in the toolbar first need to create a menu item layout in the XML -> menu. The menu layout is where the list of menu items is described in XML format. This XML layout will hold the menu item’s title, id, icons and other pieces of information. Let’s see a brief about the attributes of a menu item.
<menu> </menu>menu attribute is the parent tag for the list of menu items.
<item> </item>item attributes is the menu item which have to shown in the application.
android:id– id attribute used to define the unique id for the menu item.
android:title– title attribute defines the title to be shown in the action bar/toolbar of the android application.
app:showAsAction– will define where to show the menu item, show it directly on the toolbar or list it under the menu icon.
app:actionViewClass– the menu item must be mentioned if it uses different view classes.
android:icon– icon attribute used to assign drawable to your menu item
After creating the menu you have to add it in the activity under
onCreateOptionsMenu like below. The
menuInfalter.inflate method is used to inflate your menu layout inside the activity or the fragment and consider it as the Menu. Then find the search menu item by its id, and assign it to the variable to access,
onQueryTextSubmit the method used will be called after the user clicks the enter/search after inputting the search query.
onQueryTextChange method is used when the change occurs in the query field.
Handling the Back press:
Since the android’s native
onBackPressed() event is called when clicking the back button as default, it results in closing/destroying the activity while the search view is opened or in us. To prevent this add the following in your code and check whether the search view is active or not before closing the current activity.
Styling the SearchView Elements:
Customization of the search view can be done by both XML and programmatic.
By adding the following style to the app theme, the search view can be customized.
In the code part use the following to change the color of searchview.
The final outcome this will be as followed
Read in Medium post.