Amit Maddheshiya
Amit Maddheshiya

Reputation: 23

Menu return null in android

Hi this is my first question. i am learning android. here i am trying to setup menu icon top menubar. I have added sets of item in menu. i want to manage icon from activity. I am trying to show hide menu icon. Menu return null in onCreate. Is there any other way to manage menu icon dynamically ? please help.

This is the activity class code snippet where i am trying to manage menu.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mMenu = (Menu) findViewById(R.id.menuBar);//here Menu return null
    mMenuItem = mMenu.getItem(2);
    mMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    mMenuItem.setVisible(true);
  }

will appreciate your help. thanks.

Upvotes: 2

Views: 1662

Answers (3)

Monir Zzaman
Monir Zzaman

Reputation: 489

Just follow the bellow instruction:

Step 1:
You need to inflate menu item from onCreateOptionsMenu(Menu menu)
Step 2:
You need a MenuInflater object that you can get using getMenuInflater() API. Like: MenuInflater inflater = getMenuInflater();
Step 3:
Inflate you menu xml file like: inflater.inflate(R.menu.menu_bottom_nav, menu);
Step 4:
You have to get menu object for specific item like : MenuItem menuItem = menu.getItem(index). Here Index is the number depending on which menu item's object you want to get.

Full code example:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.menu_bottom_nav, menu);

      MenuItem menuItem  = menu.getItem(0);

     return true;
}

Upvotes: 0

Randyka Yudhistira
Randyka Yudhistira

Reputation: 3652

Dont put it on your onCreate because your menu is initialized in onCreateOptionsMenu

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.your_menu, menu);
    mMenuItem = menu.getItem(2);
    mMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    mMenuItem.setVisible(true);
    return true;
}

Upvotes: 1

Kapil Rajput
Kapil Rajput

Reputation: 11545

First inflate menu to get MenuItem in activity method onCreateOptionsMenu and then try to get menu.getItemlike this :

    @Override
   public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    getMenuInflater().inflate(R.menu.menu_activity, menu);
   MenuItem item=menu.getItem(2);
   item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
   item.setVisible(true);
    return true;
}

Upvotes: 1

Related Questions