简体   繁体   中英

Change menu at run-time

How do I change the options menu at run-time in android 2.3.3? I have two xml menus and need to switch menu type at run-time.

I would like to destroy or update the menu and when the user then presses the menu button, onCreateOptions menu is then called again selecting the appropriate xml menu.

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    if(OPTIONS_TYPE == 0) // Photo option
        getMenuInflater().inflate(R.menu.photomenu, menu);
    else // Photo + delete option
        getMenuInflater().inflate(R.menu.photodeletemenu, menu);

    return super.onCreateOptionsMenu(menu);
}

The onCreateOptionsMenu only gets called once. There may be a hack that lets you remove an options menu, but the standard way to modify it after that call is as follows from the android docs, note that it says "must"

Changing menu items at runtime

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method.

Documentation is at Creating Menus

Now having said that you can do this, just not sure if it's supported. This is just my own test code where I swap the menus each time, you will need to add your own logic

@Override
public boolean onPrepareOptionsMenu (Menu menu) {

    menu.clear();

    if (OPTIONS_TYPE == 0) {
        OPTIONS_TYPE = 1; 
        getMenuInflater().inflate(R.menu.secondmenu, menu);

    }
    else { // Photo + delete option {
        OPTIONS_TYPE = 0;
        getMenuInflater().inflate(R.menu.firstmenu, menu);
    }

    return super.onPrepareOptionsMenu(menu);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM