I'm describing the whole procedure of adding search view to action bar.This snippets of code worked for me.
Add search view in menu:add the following item in the menu layout of the activity in which you require search view.
<item
android:id="@+id/search"
android:title="@string/search_title"
android:icon="@drawable/ic_action_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView"/>
Note: menu layout file should contain following schema.
xmlns:app="http://schemas.android.com/apk/res-auto"
Create a Searchable Configuration:
create a file searchable.xml in the directory res/xml.
copy the following code into it.
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint" />
Modify onCreateOptionsMenu() method:
In the onCreateOptionsMenu() method of your activity, associate the searchable configuration with the SearchView by calling setSearchableInfo(SearchableInfo):
Your onCreateOptionsMenu should look like this.
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_display_cards, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
//SearchView searchView =
// (SearchView) menu.findItem(R.id.search).getActionView();
MenuItem mSearchMenuItem = menu.findItem(R.id.search);
SearchView searchView =
(SearchView)MenuItemCompat.getActionView(mSearchMenuItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(
new ComponentName(getApplicationContext(),
SearchResultsActivity.class)));
return true;
}
Make an activity SearchResultsActivity to show the results of your search.
In the manifest file ,add the following
<activity
android:name=".SearchResultsActivity"
android:label="@string/title_activity_search_results" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable"
android:value=".SearchResultsActivity"/>
</activity>
Your SearchResultsActivity should implement the following methods
@Override
protected void onNewIntent(Intent intent) {
...
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data and show it in
//SearchResultsActivity
}
}
Note:You should call the following from onCreate method of SearchResultsActivity
handleIntent(getIntent());