i need to be able to change the options menu (the one that is shown upon pressing the menu button) on android , so that on one case (for example upon a button being pressed) , it will use a specific menu resource (XML file as in /res/menu/... ) for the menu , and on another case , use a different XML file.
so far i've seen only examples of doing it without xml (example here and here) , and they worked fine , but i want to be able to change the entire menu on some cases. i've tried to modify the solutions i've found , but none of my trials worked.
if possible , i would prefer to re-create the menu only if the it needs to be updated with a menu resource that is different from the current one.
please help me.
Android Studio provides a standard XML format for the type of menus to define menu items. We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application.
In android, we can handle options menu item click events using the onOptionsItemSelected() event method. Following is the example of handling a options menu item click event using onOptionsItemSelected().
If you want to change the Options Menu any time after it's first created, 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 refer to the which menu you want to display depending on your requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With