Good day.
I have a MainMenu class in my application that contains a sidebar and a FrameLayout for displaying fragments, one of the fragments contains a ViewPager , which is filled with fragments. One of these fragments has its own action bar menu , if I click on the toolbar item and then open the side menu and switch to another fragment, then in this fragment, when I click on the toolbar item, the OnOptionsItemSelected old fragment is OnOptionsItemSelected . It shows even debugging.
In each fragment when drawing I call menu.clear() . The icons are displayed correctly, but the actions are not the same when clicked.
This is how the toolbar menu is processed in any of the fragments:
public class MyBodyPhoto extends Fragment { @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ... setHasOptionsMenu(true); return v; } private View.OnClickListener photoClick = new View.OnClickListener() { @Override public void onClick(View view) { if(canDelete) showPhotoToDelete((ImageView) view, (boolean)view.getTag()); } }; @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // inflater.inflate(R.menu.menu_main, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public void onPrepareOptionsMenu(Menu menu) { menu.clear(); if(canDelete){ addPhotoView.setVisibility(View.GONE); MenuItem conf = menu.add("Подтвердить"); conf.setIcon(android.R.drawable.ic_menu_save); conf.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS); MenuItem cancel = menu.add("Отменить"); cancel.setIcon(android.R.drawable.ic_menu_close_clear_cancel); cancel.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS); ((MainMenu) getActivity()).getSupportActionBar().setTitle("Выбрано: " + imagesToDelete.size()); } else{ MenuItem mi = menu.add("Удалить"); mi.setIcon(android.R.drawable.ic_menu_delete); mi.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS); ((MainMenu)getActivity()).getSupportActionBar().setTitle("Мое тело"); } super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement CharSequence title = item.getTitle(); if (title.equals("Отменить")) { getActivity().invalidateOptionsMenu(); canDelete = !canDelete; } else {// if (title.equals("Редактировать")) { getActivity().invalidateOptionsMenu(); canDelete = !canDelete; return true; } return super.onOptionsItemSelected(item); }