I have a fragment that contains a search menu in the toolbar. when user first time click on navigation item, Fragment
is added in activity which uses add
method of FragmentManager
and then it will be show
, hide
or remove
from fragment container according to the logic.
My problem is when the first time I click on navigation item search menu is displayed in the toolbar but afterwards when I come back to this fragment, sometimes there will be blank toolbar without search menu. How can I solve this?
Here is the main part code of fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
searchFragmentInstance = this;
filterManager = new FilterManager();
//set toolbar
Toolbar toolbar = view.findViewById(R.id.toolbar_search);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
//other code...
return view;
}
Display search menu in toolbar using this:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onPrepareOptionsMenu(menu);
inflater.inflate(R.menu.search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) getContext().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) item.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
//other code...
}