问题
I have a layout which has 2 fragments. These fragments uses the same menu, because I have another layouts that has only one of these (used in small screen device).
My problem is menu items of each fragments shows in the menu, and since they're from the same menu, they are duplicated to each others. I need to display only menu from one fragment, not both. Is there anyway I could archive this ?
Or, probably better, create 2 different menu. One for the layouts that has one of these fragment alone (which is used in small-screen device), and another one for layout having both fragments. How could I do this ?
Edit: I use ActionBarSherlock library for backward compatibility, and I test it on the Android 3.0 emulator.
回答1:
I've found the not-so-good solution. In onCreateOptionsMenu() of each fragment, call menu.clear() to remove any existing menu item before inflate the menu.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
This would post the future problems. I may decide to uses different menus for each fragments, which each menus share menu items. I think we can manipulate the menu at the onCreateOptionsMenu(), but currently I don't know how to get the menu item associated with the fragment before inflate it with MenuInflater.
回答2:
I'm late but maybe it can help others. This sounds like a design smell (if this term exists).
If both fragments have same menu items, and it doesn't matter which fragment's items are used (that is, it makes no difference if you click item 1 of fragment A, or item 1 of fragment B), then probably the menu should not be part of the fragment, but of the activity. That would solve the duplication.
回答3:
do you call the super method of createOptionMenu?
- then it can happens that alls optionmenus are shown.
回答4:
I found a work around, that it working for me. In onOptionsItemSelected method, first i do its check if the class its equal to or not to the class i get from the fragmentManager with findFragmentById(R.id.content_frame).getClass()
I got something like this
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if( this.class != getFragmentManager().findFragmentById(R.id.content_frame).getClass() ) {
return false; // must do nothing
}
// do your menu stuff
}
来源:https://stackoverflow.com/questions/8472776/fragments-with-the-same-menu-on-the-same-layout-cause-duplicated-menuitem