Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments, with the same menu, on the same layout cause duplicated menuitem

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.

like image 504
mr_tawan Avatar asked Dec 12 '11 10:12

mr_tawan


1 Answers

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.

like image 166
mr_tawan Avatar answered Sep 21 '22 03:09

mr_tawan