Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set visibility for an actionbar menu group?

UPDATE

Originally I was using ActionBarSherlock I have since created a brand new project using a native android action bar just to test this and I am still getting the same problem.

I am successfully showing/hiding items but not groups. I am rapidly coming to the conclusion that there is a bug in the ActionBar and it is not possible to programmatically set the visibility of a group

END of UPDATE

Given the following menu When accessing the Group I get a null pointer exception

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@+id/action_settings"
        android:title="@string/settings"
        android:orderInCategory="100"
        android:showAsAction="never"/>

        <group android:id="@+id/mnu_text_group"
           android:visible="false">
            <item android:id="@+id/mnu_text_type"
                android:enabled="true" 
                android:visible="true"
                android:icon="@drawable/ic_action_text_icon"
            android:showAsAction="always"> 
            </item>
            <item android:id="@+id/text_color"
                android:enabled="true" 
                android:visible="true" 
                android:showAsAction="always" 
                android:icon="@drawable/ic_action_color_line">
            </item>
        </group>        
    <item android:id="@+id/mnu_images"
...

In the onPrepareOptionsMenu of the relevant activity I have

public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem mnuTextGroup = menu.findItem(R.id.mnu_text_group);
    mnuImage.setEnabled(mEnableImageMenu);
    mnuTextGroup.setVisible(false);
    ...

The call to mnuTextGroup.setVisible(false); raises a null pointer exception

However, by changing the find method to find an item within the group works fine e.g. MenuItem mnuTextGroup = menu.findItem(R.id.mnu_text_type);but obviously this works just for the specific item. I know groups are designed for exactly this purpose, to be able to set the visibility of and enable/disable all items within the group but I have been unable to find a way to do this programatically.

like image 353
jamesc Avatar asked Feb 05 '14 20:02

jamesc


2 Answers

Finally found the solution I needed to use the setGroupVisible() method of the menu object passed into the onPrepareOptionsMenu() method

This is what worked for me

Instead of

MenuItem mnuTextGroup = menu.findItem(R.id.mnu_text_group);
mnuImage.setEnabled(mEnableImageMenu);
mnuTextGroup.setVisible(false);

This is what I needed

menu.setGroupVisible(R.id.mnu_text_group, false);
like image 185
jamesc Avatar answered Oct 09 '22 21:10

jamesc


Simple and one line

navigationView.getMenu().setGroupVisible(R.id.groupstaff, false);
like image 44
Gautam Surani Avatar answered Oct 09 '22 20:10

Gautam Surani