Very Quick way to add Search to your Apps

satya - 12/3/2014, 4:24:25 PM

SearchView is the key class for this. Here is the link to that API

SearchView is the key class for this. Here is the link to that API

satya - 12/3/2014, 4:25:13 PM

Here is how you add Search as a menu item to the actionbar


@Override 
    public boolean onCreateOptionsMenu(Menu menu) {
        // Place an action bar item for searching.
        MenuItem item = menu.add("Search");
        item.setIcon(android.R.drawable.ic_menu_search);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        SearchView sv = new SearchView(this);
        sv.setOnQueryTextListener(this);
        item.setActionView(sv);
        return true;
    }

satya - 12/3/2014, 4:26:18 PM

Your activity needs to implement the query listener like this


public class TestLoadersActivity 
extends MonitoredListActivity
implements LoaderManager.LoaderCallbacks<Cursor>, OnQueryTextListener

satya - 12/3/2014, 4:27:32 PM

Implement the callbacks


public boolean onQueryTextChange(String newText) {
        // Called when the action bar search text has changed.  Update
        // the search filter, and restart the loader to do a new query
        // with this filter.
        mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
        getLoaderManager().restartLoader(0, null, this);
        return true;
    }

    @Override 
    public boolean onQueryTextSubmit(String query) {
        // Don't care about this.
        return true;
    }

satya - 12/3/2014, 4:29:15 PM

The code inside callbacks is copy/paste, but you can do what ever you want!

The code inside callbacks is copy/paste, but you can do what ever you want!