void74 void74 - 1 month ago 9
Android Question

Get the ID of a MenuItem in a toolbar

I have a "menu" resource "menu_test" with the following code:

<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".TestActivity" >

<item android:id="@+id/hideshow"
android:title="Body visbility"
android:orderInCategory="100"
android:icon="@drawable/showicon"
app:showAsAction="always" />

</menu>


In my activity.java I inflate the toolbar in the "onCreate" function and add a click listener:

private Toolbar toolbar;
...
toolbar = (Toolbar)findViewById(R.id.toolbarId);
toolbar.inflateMenu(R.menu.menu_test);
toolbar.setOnMenuItemClickListener(this);


I would like to get the ID of "hideshow" and change the icon:

testItem = (MenuItem) toolbar.findViewById(R.id.hideshow);
testItem.setIcon(R.drawable.hideicon);


However to app crashes when getting the ID in the first line. In the click listener function it works fine, since the ID is provided internally with the click:

public boolean onMenuItemClick(MenuItem item)
item.setIcon(R.drawable.hideicon);


So how can I change the icon within the onCreate function? ("findItem" does not work, since toolbar is not a menu)

Answer

I may be easier to add the menu items programmatically so you can maintain a reference to them:

public class MainActivity extends AppCompatActivity {

    private static final int MENU_SETTINGS = Menu.FIRST;
    MenuItem menuItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menuItem = menu.add(0, MENU_SETTINGS, 0, R.string.action_settings).setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_SETTINGS:
                // DO SOMETHING
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
Comments