You have to add the SearchView only in the searchFragment:
searchFragment class:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
...
setHasOptionsMenu(true);
.....
return rootView ;}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_search, menu);
try {
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
// do your search
return false;
}
@Override
public boolean onQueryTextChange(String s) {
// do your search on change or save the last string or...
return false;
}
});
}catch(Exception e){e.printStackTrace();}
}
menu_search xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_search"
android:icon="@drawable/action_search_btn"
android:title="Search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…