-3

I want to clarify that I talk about a navigation drawer menu and not an action button icon.

I need to change an menu icon programmatically. For this I done next:

private Menu menu;

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

.... and I try to change icon item with :

 menu.getItem(6).setIcon(getResources().getDrawable(R.mipmap.ic_flash_on_black_24dp));

Unfortunately the item remain unchanged. Can help me to solve problem please?

I have observed that getDrawable is deprecated but no ideea how to use the new one.

General Grievance
  • 4,555
  • 31
  • 31
  • 45

2 Answers2

1

The answer was very simple:

private Menu menu; 

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

    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
    navigationView.setNavigationItemSelectedListener(this);

    menu = navigationView.getMenu();

...

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.nav_light) {
       if (canTorch) {
           try {
               if (isTorchOn) {
                   turnOffFlashLight();
                   isTorchOn = false;
                   menu.getItem(6).setIcon(getResources().getDrawable(R.mipmap.ic_flash_on_black_24dp));
               } else {
                   turnOnFlashLight();
                   isTorchOn = true;
                   menu.getItem(6).setIcon(getResources().getDrawable(R.mipmap.ic_flash_off_black_24dp));
               }
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

All was about : menu = navigationView.getMenu();

0

Try to place icon modification code in onPrepareOptionsMenu method:

Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.

Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53