Android 动态更改 ActionBar 中的图标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11006749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:42:05  来源:igfitidea点击:

Change icons in ActionBar dynamically

androidandroid-actionbar

提问by Andres

I have an Activitywhich has an ActionBarbut I need to change the icons on the ActionBardynamically, I have a pauseand a playbutton and I need to replace the playbutton with the pausebutton as the user click on it. I have searched and I found it:

我有一个ActivityActionBar但我需要ActionBar动态更改图标,我有一个暂停和一个播放按钮,当用户单击它时,我需要用暂停按钮替换播放按钮。我已经搜索并找到了它:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if(DEBUG) Log.i("onCreateOptionsMenu()", "onCreateOptionsMenu() -> LogicAnalizerView");
    //menu.add("").setIcon(R.drawable.pause).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.actionbarlogic, menu);
    menu.removeItem(R.id.pauseLogic);

    return true;
}

So in this way I remove the Pausebutton and I can add it too, but it only happen when I start the Activityand the ActionBaris drawn. How can I force to redraw the ActionBar? Also, on this way the whole ActionBaris redrawn. Is that right? Is any way to redraw only the button/icon I want?

所以通过这种方式,我删除了暂停按钮,我也可以添加它,但它只在我启动ActivityActionBar绘制时发生。我怎样才能强制重绘ActionBar?此外,以这种方式ActionBar重新绘制整体。那正确吗?有没有办法只重绘我想要的按钮/图标?

Thank you :)

谢谢 :)

回答by chubbsondubs

You'll have to save off a reference to the MenuItem after doing the inflation. So something like the following:

完成膨胀后,您必须保存对 MenuItem 的引用。所以类似于以下内容:

public boolean onCreateOptionsMenu( Menu menu ) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate( R.menu.actionbarlogic, menu );
    playMenu = menu.findItem(R.id.playMenu);
    updatePlayStatus();
    return menu;
}

public void updatePlayStatus() {
    if( playService.isConnected() ) {
        playService.isPlaying() ? playMenu.setIcon(R.drawable.pause) : playMenu.setIcon(R.drawable.play);
    }
}

Then you can refer to the playMenu anytime. So you can modify the item as say your player finishes playing and should go back to a play icon.

然后你可以随时参考playMenu。因此,您可以修改项目,例如您的播放器完成播放并且应该返回播放图标。

回答by Sandy D.

Instead of removing them, you could just hide the button you don't want displayed.

您可以隐藏不想显示的按钮,而不是删除它们。

For example:

例如:

private boolean isPlaying;
MenuItem mPlayMenuItem;
MenuItem mPauseMenuItem;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.actionbarlogic, menu);

    mPlayMenuItem = menu.findItem(R.id.action_play);
    mPauseMenuItem = menu.findItem(R.id.action_pause);

    return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.action_play:
            isPlaying = true;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                this.invalidateOptionsMenu();
            }
            return true;
        case R.id.action_pause:
            isPlaying = false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                this.invalidateOptionsMenu();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}


 @Override
public boolean onPrepareOptionsMenu (Menu menu) {
    super.onPrepareOptionsMenu(menu);

    if (isPlaying) {
        mPlayMenuItem.setVisible(false); // hide play button
        mPauseMenuItem.setVisible(true); // show the pause button
    } else if (!isPlaying) {
        mPlayMenuItem.setVisible(true); // show play button
        mPauseMenuItem.setVisible(false); // hide the pause button
    }

    return true;
}

Just a note, this:

只是一个注释,这个:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     this.invalidateOptionsMenu();
}

is required to update the action bar. After 3.0 devices, the action bar does not automatically update itself. So, you have to manually tell it to call the "OnPrepareOptionsMenu(Menu)" so that it will refresh the items by calling the "Activity.invalidateOptionsMenu()".

需要更新操作栏。在 3.0 设备之后,操作栏不会自动更新自身。因此,您必须手动告诉它调用“OnPrepareOptionsMenu(Menu)”,以便它通过调用“Activity.invalidateOptionsMenu()”来刷新项目。

Hope this helps!

希望这可以帮助!

Reference: http://developer.android.com/reference/android/app/Activity.html#onPrepareOptionsMenu(android.view.Menu)

参考:http: //developer.android.com/reference/android/app/Activity.html#onPrepareOptionsMenu(android.view.Menu)

http://developer.android.com/reference/android/support/v4/app/ActivityCompat.html#invalidateOptionsMenu(android.app.Activity)

http://developer.android.com/reference/android/support/v4/app/ActivityCompat.html#invalidateOptionsMenu(android.app.Activity)

回答by David

private Menu mMenu;

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main_activity, menu);

    // Save the menu reference
    mMenu = menu;
    return super.onCreateOptionsMenu(menu);
}

// For example - Call when you need to change icon
private void setActionIcon(boolean showWithBadge)
{
    MenuItem item = mMenu.findItem(R.id.ITEM_ID);

    if(mMenu != null)
    {
        if(showWithBadge)
        {
            item.setIcon(R.drawable.IC_WITH_BADGE);           
        }
        else 
        {
            item.setIcon(R.drawable.IC_WITHOUT_BADGE);
        }
    }
}

回答by Mallow66

If you want to get the first item from your menu, **

如果您想从菜单中获取第一项,**

use menu.getItem(0);

use menu.getItem(0);

this Code woks perfectly :

这段代码完美地工作:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
       MenuItem m =  menu.getItem(0);
       m.setIcon(R.drawable.your_icon_here);
    }


    return true;
}

回答by Mohit Atray

Use invalidateOptionsMenu() method.

使用 invalidateOptionsMenu() 方法。

private boolean isPlaying;

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.actionbarlogic, menu);
    if (isPlaying) menu.removeItem(R.id.play_button);
    else menu.removeItem(R.id.pause_button);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.play_button:
            // Do what the play button should do here
            isPlaying = true;
            break;

        case R.id.pause_button:
            // Do what the pause button should do here
            isPlaying = false;
            break;
    }
    invalidateOptionsMenu();
    return true;
}

回答by Parinda Rajapaksha

Override the onPrepareOptionsMenuin your activity class and then you can add/ remove or visible/invisible menu items.

覆盖onPrepareOptionsMenu您的活动类中的 ,然后您可以添加/删除或可见/不可见的菜单项。