get menuitem in oncreate or onresume

Viewed 1717

I need disable menu item on specific function and i have tried with some code like:

public class ExampleActivity extends AppCompatActivity
    Menu menu;

then assign here

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    this.menu = menu;
    return true;
}

Then later use assigned Menu object to get required items

menu.findItem(R.id.avviapc).setEnabled(false);

or:

MenuItem avviopc;

public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.right_home, menu);
        avviopc = menu.getItem(R.id.avviapc);
        return true;
    }

avviopc.setEnabled(false);

But i have alway crash:

java.lang.IndexOutOfBoundsException: Index: 2131296295, Size: 3
                      at java.util.ArrayList.get(ArrayList.java:411)
                      at android.support.v7.view.menu.MenuBuilder.getItem(MenuBuilder.java:741)

or:

Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference

I call: menu.findItem(R.id.avviapc).setEnabled(false); onCreate or onResume if specific value in if is true.

If call after 2/3 second after activity start with manual button the code work.

3 Answers

MenuItem.getItem(index) take index of the menu item. If you want to take the id to reference the item use MenuItem.findItem:

avviopc= menu.findItem(R.id.avviapc); //item id

avviopc= menu.getItem(indexOfavviopc); //item index

Call your method in onCreateOptionsMenu to solve the index error:

avviopc= menu.findItem(R.id.avviapc); // Do not use  getItem(position)

But if you also know the position of your menu item lets say they are three and you want the third one then:

avviopc = menu.getItem(2);

Description:

getItem(int) wants a position of the menu item for that menu.

findItem(int) wants the resource id of the menu item.

Related