Android invalidateOptionsMenu() for API < 11
I used ActivityCompat.invalidateOptionsMenu(MainActivity.this);
so that my menu item "refresh" can automatically be enabled/disabled without the using have to touch the "Menu" option (imagine the user leaves the Menu open... I need the "Refresh" menu item to automatically disabled and enable itself).
The ActivityCompat.invalidateOptionsMenu(MainActivity.this)
works fine in Android 11+. But what can I use for android API < 11 ? :S I've searched so much but I cannot find an answer. Can anyone please help me on this?
This works fine in Android API 11+, using the onPrepareOptionsMenu
and ActivityCompat.invalidateOptionsMenu(MainActivity.this)
.
The issue is trying to get it done in Android API < 11.
Here is my onPrepareOptionsMenu
method:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(menuRefreshEnable){
menu.getItem(0).setEnabled(true);
}
if(!menuRefreshEnable){
menu.getItem(0).setEnabled(false);
}
return true;
}
Solution 1:
On API < 11
use supportInvalidateOptionsMenu()
method
Solution 2:
ActivityCompat.invalidateOptionsMenu()
doesn't callback onPrepareOptionsMenu();
it just update the menu directly. Just put some Log.d()
and check out by yourself.
This works for me (I'm using API 8):
private Menu mMenu;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.track_fragment, menu);
mMenu = menu;
}
...
private void someMethod() {
...
if (mMenu != null) {
MenuItem item = mMenu.findItem(R.id.new_track);
if (item != null) {
item.setVisible(false);
ActivityCompat.invalidateOptionsMenu(this.getActivity());
}
}
...
}
My someMethod()
get called from several places, even before onCreateOptionsMenu()
, so I must check mMenu != null
.