zpwrsg
Last Updated: August 04, 2017
·
138.7K
· itseranga
892414 10151468467596730 1847316210 o

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

Say Thanks
Respond

6 Responses
Add your response

18848
0xnvztpa normal

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 ·
19858
Vl3tarav normal
over 1 year ago ·
20825
0 fo2qejdzqoinqamxtsyveysv6wnfqhmxdd4jeyjhjmc9mumk 2pexos6hl9jlf7hadaz5jbwxogj

A clear number of responsibilities must be achieved by a person trying to get these kinds of advancements to ensure that they are eligible to make an application for these kinds of loans. Anyone thinking about trying to get these kinds of advancements should automatically become a person regarding England.Doorstep loans, short term loans
http://www.shorttermdoorsteploans.co.uk
http://www.badcreditdoorsteploans.org.uk

over 1 year ago ·
21439
None

thank you!

over 1 year ago ·
28584

Hi Dear,

This is really good explanation of the Add search function to list view in android apps. This tips and coding part is really good for beginners.

Thanks for sharing.

http://bit.ly/2kGE7G0

6 months ago ·
28792

where did you store the values listed during search?

4 months ago ·