Android 如何在运行时添加操作栏项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10322848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:18:03  来源:igfitidea点击:

How can I add an Action Bar Item during run time

androidandroid-actionbaractionbarsherlock

提问by hdoria

How can I add an Action Bar Item during run time?

如何在运行时添加操作栏项?

I am using actionBarSherlock, and I need to add some buttons when an event occurs (get some texts from a RSS, for example). I can't rely on a fixed xml.

我正在使用actionBarSherlock,并且我需要在事件发生时添加一些按钮(例如,从 RSS 获取一些文本)。我不能依赖固定的 xml。

回答by Tony

You can create the menu in code like this:

您可以在代码中创建菜单,如下所示:

/*************************************/
/* Create the actionbar options menu */
/*************************************/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    menu.add(0, 0, 0, "History").setIcon(R.drawable.ic_menu_recent_history)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    menu.add(0, 1, 0, "Settings").setIcon(R.drawable.ic_menu_manage)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

    return true;
}

Inside check for a boolean.

内部检查布尔值。

You will need to call supportInvalidateOptionsMenu() to recreate the menu.

您需要调用 supportInvalidateOptionsMenu() 来重新创建菜单。

回答by dymmeh

You can maintain a flag that determines if you need to display your button

您可以维护一个标志来确定是否需要显示您的按钮

boolean hasRss = false;

then, override the method onCreateOptionsMenu(Menu menu) and check to see if hasRss is true or false. If true, add your button to do whatever. Then you can add your normal buttons you want to always show up regardless if you have the RSS or not

然后,覆盖方法 onCreateOptionsMenu(Menu menu) 并检查 hasRss 是真还是假。如果为 true,请添加您的按钮以执行任何操作。然后你可以添加你想要总是显示的普通按钮,无论你是否有 RSS

 @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
       if (hasRss)
       {
           menu.add(Menu.NONE, 0, Menu.NONE, "View RSS").setIcon(R.drawable.ic_menu_view)
                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
       }

       menu.add(Menu.NONE, 1, Menu.NONE, "Normal button that is always there").setIcon(R.drawable.ic_menu_button)
                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

    }

you will have to set your hasRss value = true whenever you retrieve your values and call invalidateOptionsMenu();to reload the action bar menu items

每当您检索您的值并调用invalidateOptionsMenu();重新加载操作栏菜单项时,您都必须设置您的 hasRss 值 = true