Maurix
Maurix

Reputation: 742

Android and ActionBarCompat: how to change visibility of actions at runtime on pre-ICS devices?

I have an Activity that extends ActionBarActivity taken from the ActionBarCompat code sample and I'm trying to show/hide menu items (actions) at runtime.

I've tried using setVisible() on the MenuItem and works for ICS, but in pre-ICS it only change visibility of menu items (menu button press) whereas the ActionBar doesn't get notified of menu changes.

Any solution? Thanks in advance!

Upvotes: 12

Views: 1972

Answers (3)

Paris
Paris

Reputation: 367

You have to call supportInvalidateOptionsMenu() which is the relevant method for an ActionBarActivity:

http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html#supportInvalidateOptionsMenu()

Upvotes: 3

Steelight
Steelight

Reputation: 3357

I created multiple alternatives of the action bar items under /res/menu/. I keep a member to indicate which one I am using right now. to replace the menu, I call:

protected void setMenuResource(int newMenuResourceId)
{
    _menuResource = newMenuResourceId;
    invalidateOptionsMenu();
}

And I override onCreateOptionsMenu() to:

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    if (_menuResource != 0)
    {
        getSupportMenuInflater().inflate(_menuResource, menu);
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

Now, if I want to change the action Items, I call:

setMenuResource(R.menu.actionbar_menu_X);

Upvotes: 5

Roger Alien
Roger Alien

Reputation: 3060

This is how i solved it:

In ActionBarHelperBase.java of actionbarcompat project

...

private View addActionItemCompatFromMenuItem(final MenuItem item) {

final int itemId = item.getItemId();

....

The creator of this class copy properties of object, but didn't copy the id of item, so it is impossible to find it later with fiven id.

So i added it in that method:

...
actionButton.setId(itemId);
...

and in the same class i just use:

@Override
public void hideMenuItemById(int id, boolean show){
    getActionBarCompat().findViewById(id).setVisibility(show? View.VISIBLE: View.GONE);
}

Hope it helps You.

Upvotes: 4

Related Questions