Android - changing menu options dynamically, but due to bloating XML

I need to change the options menu (the one that appears when the menu button is pressed) on Android, so in one case (for example, when the button is pressed) it will use a certain menu resource (XML file as in / res / menu / ...) for the menu, or in another case, another XML file.

so far I have only seen examples of this without xml (an example here and here ), and they worked fine, but I want to be able to change the entire menu in some cases. I tried to change the solutions I found, but none of my tests worked.

if possible, I would prefer to recreate the menu only if it should be updated by a menu resource that is different from the current one.

please help me.

+7
source share
1 answer

If you want to change the options menu at any time after creating it, you must override the onPrepareOptionsMenu () method.

public boolean onPrepareOptionsMenu (Menu menu) { menu.clear(); if (CASE_1 == 0) { CASE_1 = 1; getMenuInflater().inflate(R.menu.secondmenu, menu); } else { CASE_1 = 0; getMenuInflater().inflate(R.menu.firstmenu, menu); } return super.onPrepareOptionsMenu(menu); } 

where CASE_1 refers to the menu that you want to display depending on your requirement.

+16
source

All Articles