android – How can I add an Action Bar Item during run time-ThrowExceptions

Exception or error:

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.

How to solve:

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.

###

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

Leave a Reply

Your email address will not be published. Required fields are marked *