Do I Have To Use Searchable Activity When Using Android's Searchview?
Both of those method should return a boolean to indicate that they consumed the action and no other action should be done from the OS's side. Looking at the source code only onQueryTextSubmit() returned values is checked but for your own peace of mind just return true
in both methods.
complete code showing the listener in action:
manifest:
Don't add anything
searchable configuration:
Need to create such xml file.
right-click your res
folder and choose new --> android resource file
. put whatever you want as file name ("searchable" will work ok, for example), and choose XML
as resource type.
Then copy & paste this code in the created file (replace the hint string with your own):
<?xml version="1.0" encoding="utf-8"?><searchablexmlns:android="http://schemas.android.com/apk/res/android"android:label="@string/app_name"android:hint="put here your hint string to be shown"
/>
menu.xml:
<itemandroid:id="@+id/searchContacts"android:icon="@drawable/ic_search_white_24dp"android:title="search"app:showAsAction="collapseActionView|always"app:actionViewClass="android.widget.SearchView"
/><!-- and of course your other menu items -->
MainActivity:
@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
implementSearch(menu);
returntrue;
}
privatevoidimplementSearch(final Menu menu) {
SearchManagersearchManager= (SearchManager) getSystemService(Context.SEARCH_SERVICE);
finalMenuItemsearchMenuItem= menu.findItem(R.id.searchContacts);
finalSearchViewsearchView= (SearchView) searchMenuItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(newSearchView.OnQueryTextListener(){
@OverridepublicbooleanonQueryTextChange(String newText){
// do whatever you want with this changed text/* ... */returntrue; // signal that we consumed this event
}
@OverridepublicbooleanonQueryTextSubmit(String query){
// do whatever you want with this submitted query/* ... */returntrue; // signal that we consumed this event
}
});
}
Notice that more problems will may arise when adding a searchView to your menu items.
For an integrated fix to one of those problems (I've encountered exactly those) -
- "search icon doesn't expand when pressed",
- "the search's edit text doesn't receive immediate focus and a second tap is needed"
- "the keyboard doesn't show up when pressing the search icon"
please refer to this SO answer.
Post a Comment for "Do I Have To Use Searchable Activity When Using Android's Searchview?"