tags:

views:

112

answers:

2

In android, I create my menu item like this?

public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(0, 0, 0, "Menu1");
        menu.add(0, 1, 0, "Menu2");
        return true;
}

How can I set all the menu item disabled programmically (in another part of the code in my activity, not in onCreateOptionsMenu() method itself)?

Thank you.

A: 

add returns a MenuItem (which you can also retrieve from the Menu object), that you can store away into a variable.

MenuItem menu1;

public boolean onCreateOptionsMenu(Menu menu) {
    menu1 = menu.add(0, 0, 0, "Menu1");
}

public void someOtherMethod() {
    if(menu1 != null) {
        // if it's null, options menu hasn't been created, so nevermind
        menu1.setEnabled(false);
    }
}
David Hedlund
That seems like the hard way to do things to me... what if you've got a whole bunch of menu items? Groups work a lot better for enabling/disabling items, plus you don't have to hold onto the MenuItem to do it.
Daniel Lew
i agree, i somehow managed to misread the post as being about a single items (although it said *all* in both title and body, hrrm). i +1'd you, yours is clearly the more efficient way
David Hedlund
+3  A: 

You can use the groupId you set to disable/enable all the menu items at once, using menu.setGroupEnabled(). So for example, since you added the items to group 0, you'd do:

menu.setGroupEnabled(0, false);

Also, if you want to dynamically modify the menu, you should hook into onPrepareOptionsMenu(). onCreateOptionsMenu() is only called once per Activity, so it's good for setting up the initial menu structure, but onPrepareOptionsMenu() should be used to enable/disable menus as necessary later in the Activity.

Daniel Lew