Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 945
Maurix Avatar asked Mar 15 '12 00:03

Maurix


3 Answers

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);
like image 102
Steelight Avatar answered Oct 04 '22 04:10

Steelight


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.

like image 38
Roger Alien Avatar answered Oct 04 '22 04:10

Roger Alien


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()

like image 21
Paris Avatar answered Oct 04 '22 03:10

Paris