Android: Multiple Option Menus in one Activity

不想你离开。 提交于 2021-02-18 05:17:10

问题


I have an Activity containing a ViewFlipper and would like to show a different option menu for each view in that ViewFlipper. That is, the type of menu displayed when the menu button is pressed would depend on the type of the current view. However, onCreateOptionsMenu() is called only once (when showing the option menu for the first time), so creating the different menus can't be implemented there. How could I solve this?

Any suggestions appreciated.


回答1:


First read about onPrepareOptionsMenu(Menu menu)

Each time the user presses the Menu on their Android device while inside one of your activities, the onPrepareOptionsMenu method is called. The first time the menu is shown (i.e. only once), the onCreateOptionsMenu method is called.

Basically, the onPrepareOptionsMenu method is where you should make any changes such as enabling/disabling certain menu items, or changing the menu item text depending on the circumstances.

So do this (Don't use onCreateOptionsMenu(Menu menu) )

//Dynamically create context Menu
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear(); //Clear view of previous menu
        MenuInflater inflater = getMenuInflater();
        if(condition_true)
            inflater.inflate(R.menu.menu_one, menu);
        else
            inflater.inflate(R.menu.menu_two, menu);
        return super.onPrepareOptionsMenu(menu);
    }


来源:https://stackoverflow.com/questions/7011210/android-multiple-option-menus-in-one-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!