I try to disable a menu group with the following code, but it doesn't work, menu items are still enabled. Can you tell me what's wrong please?
res/menu/menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/a" android:title="A"></item>
<item android:id="@+id/b" android:title="B">
<menu>
<item android:id="@+id/c" android:title="C" />
<item android:id="@+id/d" android:title="D" />
<group android:id="@+id/group_1">
<item android:id="@+id/e" android:title="E" />
<item android:id="@+id/f" android:title="F" />
</group>
</menu>
</item>
</menu>
Java:
public boolean onPrepareOptionsMenu (Menu menu) {
menu.setGroupEnabled (R.id.group_1, false); // does not work
menu.setGroupVisible (R.id.group_1, false); // does not work either
return super.onPrepareOptionsMenu (menu);
}
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater ().inflate (R.menu.menu, menu);
return true;
}
To disable a menu item, set its Enabled property to False. In the following example, an event handler is attached to the OnClick event for the Edit item on a child form's menu bar. It sets Enabled for the Cut, Copy, and Delete menu items on the Edit menu based on whether RichEdit1 has selected text.
If you want to change the visibility of your menu items on the go you just need to set a member variable in your activity to remember that you want to hide the menu and call invalidateOptionsMenu() and hide the items in your overridden onCreateOptionsMenu(...) method.
If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application. E.g.
Thanks to user432209's info, here is the answer:
menu.findItem (R.id.b).getSubMenu ().setGroupVisible (R.id.group_1, false);
I'm not sure if you can use a group like this, but try this (its worth a shot):
MenuItem item = menu.findItem(R.id.group_1);
item.setVisible(true);
item.setEnabled(false);
Edit: Your problem is your menu structure and how you create the menu inside onCreateOptionsMenu
due to using parent/child menus.
You create a menu for the parent menu, not the child menu, so that is why the call to setGroupEnabled
and setGroupVisible
fail. You need to create an object in onCreateOptionsMenu
that represents the child in order for that object to be passed into onPrepareOptionsMenu
and your code to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With