开发者

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.onCreateOptionsMen开发者_运维百科u(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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜