Alex Rivera | Logout

Change icons in ActionBar dynamically

Asked 2012-06-13T00:35:10.087
60

I have an Activity which has an ActionBar but I need to change the icons on the ActionBar dynamically, I have a pause and a play button and I need to replace the play button with the pause button as the user click on it. I have searched and I found it:

@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 Pause button and I can add it too, but it only happen when I start the Activity and the ActionBar is drawn. How can I force to redraw the ActionBar? Also, on this way the whole ActionBar is redrawn. Is that right? Is any way to redraw only the button/icon I want?

Thank you :)

Edit
Report

1 Answer

56

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

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.

answered 2012-06-13T00:55:38.690

Your Answer