I have an Activity that has 2 fragments. Both are ListFragments and both contribute MenuItems to the Menu. I have one MenuItem that I've set the attribute android:showAsAction to have it show as a button on the ActionBar. Which works fine.
Now the MenuItem is state dependent. It's a Pause/Resume menu option for pausing and resuming a queue. My problem is I can't figure out how to set it's initial statue when the Fragment is created.
It's state is dependent on the whether the queue is paused or not. So I have an AsyncTask that gets the queue and sets a boolean (paused) based on the state of the queue. I'm calling onPrepareOptionsMenu to set the text for the Pause menu item based on the last known state of the queue and this works great if I leave the MenuItem in the actual menu. You tap the menu icon and onPrepareOptionsMenu is fired and the menu is updated before it's displayed.
The problem is, if I put that same MenuItem on the ActionBar (showAsAction), how can I force it to update without having to call onPrepareOptionsMenu? I need to be able to do this because on first launch of the app, I send a request to get the queue, but the task returns after the ActionBar is setup and displayed. I've created a handler in my fragment that gets called every time I get a queue update, but from there, how can I update the text for my MenuItem on the ActionBar? I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.
Rob W.
I have used this code:
And worked like a charm to me you can find OnPrepareOptionsMenu here
For clarity, I thought that a direct example of grabbing onto a resource can be shown from the following that I think contributes to the response for this question with a quick direct example.
In this case you hold onto a MenuItem reference at the beginning and then change the state of it (for icon state changes for example) at a later given point in time.
in my case:
invalidateOptionsMenu
just re-setted the text to the original one, but directly accessing the menu item and re-writing the desire text worked without problems:due to the comment below, I was able to access the menu item via the following code:
Option #1: Try
invalidateOptionsMenu()
. I don't know if this will force an immediate redraw of the action bar or not.Option #2: See if
getActionView()
returns anything for the affectedMenuItem
. It is possible thatshowAsAction
simply automatically creates action views for you. If so, you can presumably enable/disable thatView
.You can hang onto the
Menu
object you were handed inonCreateOptionsMenu()
. Quoting the docs:First please follow the two lines of codes to update the action bar items before that you should set a condition in oncreateOptionMenu(). For example:
In Kotlin 1.2 simply call:
and the
onCreateOptionsMenu
function will be called again.