Search code examples
javaandroidfragmentmenuitemaction-menu

Android set menu items dynamically at startup


I need to change the title of a menu item in my action bar at startup based on a few variables which get created at the startup. But for some reason I cant simply do that since the menu items take time to inflate maybe? how do I get around this issue. below is my attempt but it throws java.lang.IndexOutOfBoundsException

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.map_fragment_action_menu, menu);
    mOptionsMenu = menu;
    mOptionsMenu.getItem(R.id.map_fragment_action_layers_0).setTitle("my title");
}

P.S. I am using a fragment, I also tried to set the title in onCreateView() method but still doesn't work.


Solution

  • You need to use the method Menu#findItem() instead.

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.map_fragment_action_menu, menu);
        mOptionsMenu = menu;
        mOptionsMenu.findItem(R.id.map_fragment_action_layers_0).setTitle("my title");
    }
    

    Menu#getItem() expects an index and not the menu item's id. For e.g, if this menu item is the first item in the menu, you would use

    mOptionsMenu.getItem(0).setTitle("my title");