How can I add an Action Bar Item during run time

2019-03-11 00:49发布

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.

2条回答
对你真心纯属浪费
2楼-- · 2019-03-11 01:07

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.

查看更多
Luminary・发光体
3楼-- · 2019-03-11 01:10

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

 @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

查看更多
登录 后发表回答