1

I got an Android application with a single activity and many fragments. What i want to do is have a menu with 2 base options which every fragment will have and let each fragment add it's own option in addition to these base 2 options. I saw how you can do it when extending Activities, but I'm not sure how to do it with fragments. As I understand, calling setHasOptionsMenu(true) will simply overwrite the Activity's menu and let the fragment has its own menu, but it will then create duplicates of the same menu option does it not?

JJ Ab
  • 492
  • 4
  • 15

1 Answers1

0

as you know following code will inflate layout to the menu in the code

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

what you can do here is have two different flavors of menu_main.xml, like this

menu_main_fragmen_1.xml & menu_main_fragmen_2.xml

each of this will have two base option followed with the option depending on the fragment they belong to.

now every time you change the fragment in the activity call invalidateOptionsMenu() this method will invoke onCreateOptionsMenu() so the menu can be redrawn. but there would be little change in this, you have to load the appropriate layout depending on the fragment

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    if(fragment_1 is loaded){
       getMenuInflater().inflate(R.menu.menu_main_fragmen_1.xml, menu);
    }else if(fragment_2 is loaded){
       getMenuInflater().inflate(R.menu.menu_main_fragmen_2.xml, menu);
    }

    return true;
}

Update

another way of solving this issue would be like this, assume you have one menu_main.xml with all the items (including 2 base options and items related to all the fragment).

in this scenario you can change the visibility of an item when does not belong to the current fragment

menu.findItem(R.id."id_of_an_item").setVisible(false); 
Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30
  • It sounds nice but isn't it actually the same as calling the setHasOptionsMenu(true) and then inflating the specific fragment's menu? I still need to have all the options I want in every menu instead of having a single menu with the base options which will load all the time and somehow have the fragment only add to that base menu which means it will have a menu with only the special items it needs without the base options. – JJ Ab Jan 06 '16 at 09:04
  • ok the answer was more like an example, what you can do is, have one layout with all the options you got and change the visibility of them depending on the fragment you have in the activity or another way of doing this is have your menu generated dynamically so you can add or delete menu depending on the fragment – Pankaj Nimgade Jan 06 '16 at 09:08