There is one Activity with multiple Fragment , but the required SearchView should only appear on certain Fragment in the ActionBar with its own logic.

But there is a problem that is not clear to me - the code of one of the Fragment :

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { Log.d(MainActivity.TAG, "create menu in fragmnt "); MenuItem searchItem = menu.add("Search"); searchItem.setIcon(android.R.drawable.ic_menu_search); searchItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); SearchView sv = new SearchView(getActivity()); sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { Log.d(MainActivity.TAG, "TextSubmit " + query); return true; } @Override public boolean onQueryTextChange(String newText) { Log.d(MainActivity.TAG, "TextChange " + newText); return true; } }); // searchItem.setActionView(sv); super.onCreateOptionsMenu(menu, inflater); } 

If you leave it as it is, the icon is displayed, if you unregister searchItem.setActionView(sv); then the icon is no longer displayed.

How to set the creation of SearchView in the fragment code?

  • In principle, there is no sense to create software, MenuItem has a setVisible () method for setting visibility, you just need to check if the required fragment matches and then hide / show your menuItem - Android Android
  • @AndroidAndroid, for example, in the Activity in the onPrepareOptionsMenu method, determine the appropriateness of the required fragment? Tell me how to do it concisely, only a similar getFragmentManager (). FindFragmentById (R.id.content_frame) .getClass (). GetName () method occurs, where content_frame is a container for fragments. - abbath0767
  • can be checked using if (ThisFragment instanceof MyFragment) like this - Android Android
  • @ Android Android Thank you, your advice helped me and came up - abbath0767

0