开发者

How can I programmatically disable all menu item in my activity

In Android, I create my menu ite开发者_JAVA百科m 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 programmatically (in another part of the code in my activity, not in onCreateOptionsMenu() method itself)?


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.


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);
    }
}


I prefer to hide them completely if they should not be used (instead of disabling them). For that I do:

menu.clear();

and to recreate it:

invalidateOptionsMenu();

This also works for menu items added from fragments.


If still relevant:

public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    for(int i=0; i<menu.size(); i++){
        menu.getItem(i).setEnabled(isMenuEnabled);
    }
}

and call invalidateOptionsMenu() then isMenuEnabled changed


If you have multiple occasions where you want to do something with all items of a menu (for example changing the 'checked' state) there is an elegant solution using Kotlin Extension Properties: (Building on top of the answer of Valery)

In one place define the property 'items' of android.view.Menu:

import android.view.Menu
import android.view.MenuItem

val Menu.items: List<MenuItem>
get() {
    val items = mutableListOf<MenuItem>()
    for (i in 0 until this.size()) {
        items.add(this.getItem(i))
    }
    return items
}

Now you can use it on any menu:

anyMenu.items.forEach { it.isEnabled = false }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜