-3

我想澄清一下,我谈论的是抽屉式导航菜单,而不是操作按钮图标。

我需要以编程方式更改菜单图标。为此,我接下来做了:

private Menu menu;

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

....我尝试用以下方式更改图标项:

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

不幸的是,该项目保持不变。请问可以帮我解决问题吗?

我观察到 getDrawable 已被弃用,但不知道如何使用新的。

4

2 回答 2

1

答案很简单:

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;
}

一切都是关于:menu = navigationView.getMenu();

于 2016-12-06T07:12:19.590 回答
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.

于 2016-12-05T17:30:25.590 回答