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 :)
Instead of removing them, you could just hide the button you don't want displayed.
For example:
Just a note, this:
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()".
Hope this helps!
Reference: 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)
You'll have to save off a reference to the MenuItem after doing the inflation. So something like the following:
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.
Use invalidateOptionsMenu() method.
If you want to get the first item from your menu, **
this Code woks perfectly :
Override the
onPrepareOptionsMenu
in your activity class and then you can add/ remove or visible/invisible menu items.