Android SearchView Example Tutorial using DataBinding

Today we will look into Android SearchView widget and develop an application that filters a ListView by the queried text. We’ll be using DataBinding to hook up the layouts in the Activities and Adapters. If you haven’t read about DataBinding refer this tutorial first for a better understanding.

Android SearchView

Android allows us to use the search functionality in our app by displaying the SearchView widget either in the ToolBar/ActionBar or inserting it into a layout. Android SearchView widget is available from Android 3.0 onwards.

The SearchView is defined in the XML layout as shown below.

There are many forms for searching in Android such as voice search, suggestions etc. In this tutorial we’ll use SearchView.OnQueryTextListener and Filterable interfaces.

The Filterable interface filters the queried text over a ListView and displays the resulted ListView rows.

OnQueryTextListener interface can detect two events.

  1. onQueryTextChange is called when the user types each character in the text field
  2. onQueryTextSubmit is triggered when the search is pressed

Android SearchView Example

Below image shows the final android SearchView example project.

android-search-view-project

The project consists of an Activity and an Adapter for the ListView.

Android SearchView Example Code

The activity_main.xml is given below. It consists of a ListView with a SearchView on top.

activity_main.xml

The MainActivity.java is given below.

In the above code, we are passing an ArrayList of Months to the List Adapter.

We’re invoking the filter method that’s defined in the adapter class every time the search query text changes.

The ListAdapter.java class looks like this.

As you can see in the above code we’re performing filtering using an inner class ValueFilter that extends the Filter class. It filters the list by checking if the search query text matches the strings given in the ArrayList.

The XML layout for the ListView row is given below.

row_item.xml

The output of the android search view application in action is given below.

android search view output, android searchview

The SearchView shown above requires us to press the search icon to activate the text field. Also, it doesn’t contain any hint/placeholder text.

Add the following code in the MainActivity to enable the SearchView by default and display a hint.

The SearchView after customising as above looks like this.

android-search-view-output-2

This brings an end to android SearchView tutorial. We’ll dive into the advanced features of SearchView in a later tutorial. You can download the Android SearchView Project from the link given below.

By admin

Leave a Reply

%d bloggers like this: