android - change options menu dynamically , but by inflating from XML
Asked Answered
T

1

8

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.

Tellford answered 8/5, 2012 at 15:43 Comment(0)
P
17

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.

Psychometry answered 8/5, 2012 at 16:5 Comment(5)
won't it mean that it will be re-created each time you show the menu , as opposed to onCreateOptionsMenu ?Tellford
yeah it will be recreated and you stated it( i would prefer to re-create the menu)Psychometry
Or you can have single xml and setVisiblity of each menu itenm to true or false as required. refer this #9030768Psychometry
is it possible to avoid re-creating the menu each time the end user is showing it? does it even matter muchTellford
you got my vote . thanks. if you know of a way to avoid re-creation of the menu, please tell me.Tellford

© 2022 - 2024 — McMap. All rights reserved.