简体   繁体   English

在运行时更改菜单

[英]Change menu at run-time

How do I change the options menu at run-time in android 2.3.3?如何在 android 2.3.3 的运行时更改选项菜单? I have two xml menus and need to switch menu type at run-time.我有两个 xml 菜单,需要在运行时切换菜单类型。

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.我想销毁或更新菜单,然后当用户按下菜单按钮时,再次调用 onCreateOptions 菜单,选择适当的 xml 菜单。

@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. onCreateOptionsMenu 只被调用一次。 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"可能有一个 hack 可以让您删除选项菜单,但是在调用之后修改它的标准方法如下 android 文档,请注意它说“必须”

Changing menu items at runtime在运行时更改菜单项

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above.活动创建后,onCreateOptionsMenu() 方法只被调用一次,如上所述。 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.如果您想在第一次创建选项菜单后随时更改它,您必须重写 onPrepareOptionsMenu() 方法。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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