Good day. There is a toolbar with displayed items from the menu.

menu.xml

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yourapp="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/button_size_plus" android:title="@string/text_plus" android:icon="@drawable/button_size_plus" yourapp:showAsAction="always" /> <item android:id="@+id/button_size_minus" android:title="@string/text_minus" android:icon="@drawable/button_size_minus" yourapp:showAsAction="always" /> </menu> 

Initialization:

 public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } 

Can you please tell me how to get access from the code for changing item icons?

    1 answer 1

    In general, the menu can be obtained something like this:

    toolbar.getMenu()

    but it is better to have boolean variables, on which the assignment of the icons in onPrepareOptionMenu() will depend and at the right time it will only be necessary to change the values ​​of the above variables and call the menu redrawing like this:

    supportInvalidateOptionsMenu()

    redefining method

     boolean someBoolean; /* Called whenever we call supportInvalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { Log.d("LOG", "onPrepareOptionsMenu called"); MenuItem item = menu.findItemById(...); if(someBoolean){//set some icon} else{//set another icon} return super.onPrepareOptionsMenu(menu); } 

    further, somewhere in the code we change

     someBoolean = !someBoolean; supportInvalidateOptionsMenu(); 
    • Thank. Could you give an example of this implementation? Something can not do the method ... - Pollux
    • @Pollux, some code added - Yuriy Spb
    • Thank you very much! I'll try - Pollux
    • Please look here. Very similar problem. - Pollux