How to change MenuItem icon in ActionBar programmatically

后端 未结 9 1517
小鲜肉
小鲜肉 2020-11-30 23:37

How to change MenuItem icon in ActionBar programmatically? I tried to use

MenuItem menuItem = (MenuItem)findViewById(R.id.action_settings);
menuItem.setIcon(         


        
相关标签:
9条回答
  • 2020-12-01 00:00

    This works for me. It should be in your onOptionsItemSelected(MenuItem item) method item.setIcon(R.drawable.your_icon);

    0 讨论(0)
  • 2020-12-01 00:04

    Instead of getViewById(), use

    MenuItem item = getToolbar().getMenu().findItem(Menu.FIRST);
    

    replacing the Menu.FIRST with your menu item id.

    0 讨论(0)
  • 2020-12-01 00:05

    Its Working

          MenuItem tourchmeMenuItem; // Declare Global .......
    
     public boolean onCreateOptionsMenu(Menu menu) 
     {
            getMenuInflater().inflate(R.menu.search, menu);
            menu.findItem(R.id.action_search).setVisible(false);
            tourchmeMenuItem = menu.findItem(R.id.done);
            return true;
     }
    
        public boolean onOptionsItemSelected(MenuItem item) {
    
        case R.id.done:
                           if(LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).getIsFlashLight()){
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    mScannerView.setFlash(false);
                                    LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(false);
                                    tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_white_32));
                                }
                            }else {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                    mScannerView.setFlash(true);
                                    LoginPreferences.getActiveInstance(CustomViewFinderScannerActivity.this).setIsFlashLight(true);
                                    tourchmeMenuItem.setIcon(getResources().getDrawable(R.mipmap.torch_cross_white_32));
                                }
                            }
                            break;
    
    }
    
    0 讨论(0)
提交回复
热议问题