Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically enable/disable hide/unhide Android ActionBar action icon

I am developing an Android application that employs a standard ActionBar.
on a certain screen i have a Filter icon that is conditionally required,
depending on characteristics of the data being displayed, e.g. some data is filterable
Others not.
i cannot find any methods on actionbar that look likely candidates for programmaticaly hiding an actionbar action icon. how can i enable/disable an actionbar action icon?
Or
how can i hide/unhide an actionbar action icon?

like image 281
Hector Avatar asked Aug 09 '13 13:08

Hector


3 Answers

You can do it by overriding the onPrepareOptionsMenu() method. Here is a small example

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    if (count < 1)
        menu.getItem(4).setEnabled(false); //disable menuitem 5
    if (!after)
    menu.getItem(1).setVisible(false); // invisible menuitem 2
    invalidateOptionsMenu();
    return true;
}

However, This method is only called whenever you click the menu button in the action bar. If you've any icons on the action bar (except menu button), clicking on that will not trigger the OnPrepareOptionsMenu() method. In order to trigger this method manually you can use the invalidateOptionsMenu() in your methods. like this

void yourMethod () {
...
invalidateOptionsMenu();
...
}
like image 151
Samuel Robert Avatar answered Oct 18 '22 15:10

Samuel Robert


Have a look at this, it shows how to change menu items at runtime.

http://developer.android.com/guide/topics/ui/menus.html#ChangingTheMenu

You could for example save the menu as a member variable of your Activity inside onCreateOpionsMenu() and then do something like this:

MenuItem item = mMenu.findItem(R.id.addAction);
item.doSomething()

when you want to change something on a specific menu item.

like image 33
Philipp Jahoda Avatar answered Oct 18 '22 16:10

Philipp Jahoda


As I understand, you need to remove the icon that shows on the action bar top left.

You can do that with this simple line of code:

final ActionBar actionBar = getActionBar();     
actionBar.setDisplayShowTitleEnabled(false);

And if you like to get rid of the app name try:

actionBar.setDisplayShowHomeEnabled(false);

Hope this helps.

like image 45
Riste Avatar answered Oct 18 '22 16:10

Riste