Last Updated: May 15, 2022
·
289.2K
· itseranga

Add search function to list view in android

Action bar with SearchView

  • Beginning with Android 3.0, android supports to add SearchView widget to your action bar. This search view can be use to search the content in a list view

More info about SearchView
http://developer.android.com/training/search/setup.html

  • Following are the implementation steps of searchable list view

Add search menu

  • Create a menu resource file with search menu item(when click on search menu item, search widget will be appear in action bar)

  • Following is an example menu resource that I have created(res/menu/search_menu.xml)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/search"
        android:title="Search"
        android:icon="@drawable/search"
        android:showAsAction="collapseActionView|ifRoom"
        android:actionViewClass="android.widget.SearchView" />
</menu>
  • In above menu item the collapseActionView attribute allows your SearchView to expand to take up the whole action bar and collapse back down into a normal action bar item when not in use

Create SearchableConfiguration

  • Searchable Configuration defines how SearchView behaves

  • Need to define it in a xml(res/xml/searchable.xml). Following is an example searchable configuration file

<?xml version="1.0" encoding="utf-8"?>
<searchable
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="Search friend">
</searchable>
  • Then add this element into a relevant activity with <meta-data> tag
<activity
    android:name=".ui.FriendListActivity"
    android:screenOrientation="portrait"
    android:configChanges="orientation"
    android:theme="@style/Theme.Yello"
    android:windowSoftInputMode="stateHidden"
    android:launchMode="singleTask"
    android:parentActivityName=".ui.SensorDetailsActivity">
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable">
    </meta-data>
</activity>
  • In my scenario I'm gonna add SearchView to FriendListActivity

Add Menu and SearchableConfiguration to activity

  • Associate searchable configuration with the SearchView in the activity class
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu, menu);

    SearchManager searchManager = (SearchManager)
                            getSystemService(Context.SEARCH_SERVICE);
    searchMenuItem = menu.findItem(R.id.search);
    searchView = (SearchView) searchMenuItem.getActionView();

    searchView.setSearchableInfo(searchManager.
                            getSearchableInfo(getComponentName()));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(this);

    return true;
}
  • Now the SearchView added to the activity. But still searching functionality not working

Picture

Add searching functionality

  • Implement SearchView.OnQueryTextListener in activity, need to override two new methods now
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
  • This interface listen to text change events in SearchView
@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    friendListAdapter.getFilter().filter(newText);

    return true;
}
  • In here onQueryTextChange function do the filtering with list adapter, In order to do the filtering, adapter need to be implement Filterable interface

  • Following is the complete implementation of list activity(FriendListActivity)

https://github.com/erangaeb/dev-notes/blob/master/android-search-list/FriendListActivity.java

Filterable adapter

  • In my scenario I have used BaseAdapter with implementing Filterable interface

  • Following is the implementation of my adapter class(FriendListAdapter)

https://github.com/erangaeb/dev-notes/blob/master/android-search-list/FriendListAdapter.java

  • In here I have defined custom Filter class FriendFilter to do the filtering, I'm filtering the list according to the name entering in SearchView

  • I have defined two array lists here. One for display in list view and other one for filtering(original list)

// original list, filtering do with this list
private ArrayList<User> friendList;

// filtered list construct by filtering the friendList
// it uses to create the list view
private ArrayList<User> filteredList;
  • Searching functionality is working now. Following is an example output of searching list

Picture

Collapse action bar SearchView programatically

  • In my scenario when list item clicks, I'm navigate to new activity ShareActivity

  • When navigating, I'm collapsing the SearchView if it is visible

private void handelListItemClick(User user) {
    // close search view if its visible
    if (searchView.isShown()) {
        searchMenuItem.collapseActionView();
        searchView.setQuery("", false);
    }

    // pass selected user and sensor to share activity
    Intent intent = new Intent(this, ShareActivity.class);
    intent.putExtra("com.score.senzors.pojos.User", user);
    this.startActivity(intent);
    this.overridePendingTransition(R.anim.right_in, R.anim.stay_in);
}

Add search view popup text while searching

  • First enable filtering on the list view
friendListView.setTextFilterEnabled(true);
  • Modify onQueryTextChange function like below
@Override
public boolean onQueryTextChange(String newText) {
    if (TextUtils.isEmpty(newText)) {
        friendListView.clearTextFilter();
    }
    else {
        friendListView.setFilterText(newText.toString());
    }

    return true;
}
  • Now search view popup will be visible when searching. Actually is displays text that typing in SearchView

Picture

Complete source code
https://github.com/erangaeb/dev-notes/tree/master/android-search-list

4 Responses
Add your response

I must say thanks to you.....:)
i have question can we add auto-complete in this search?if yes can u provide me any link or something that i can refer?Again thank u very much.

over 1 year ago ·

thank you!

over 1 year ago ·

where did you store the values listed during search?

over 1 year ago ·

Hi,
Thanks for sharing.
my problem is when i search "iya" from your list also it is displaying the results.i don't want like this .how can i remove this.

over 1 year ago ·