47

I'm trying to update the menu buttons of my app every time one of them is pressed; in API 11+, you need to call invalidateOptionsMenu() to do this; since I want my app to be compatible with lower APIs, how do I only call this method when using api 11+?

yuttadhammo
  • 5,069
  • 6
  • 34
  • 45

6 Answers6

103

Use

ActivityCompat.invalidateOptionsMenu(Activity activity)

from the compatibility library.

Czechnology
  • 14,832
  • 10
  • 62
  • 88
candrews
  • 1,995
  • 1
  • 16
  • 13
44

For the others who are looking for an answer like I was:

If you are using ActionBarSherlock and trying to refresh the action bar buttons on API <11, instead of

Activity.invalidateOptionsMenu()

you can use

SherlockActivity.supportInvalidateOptionsMenu():

Czechnology
  • 14,832
  • 10
  • 62
  • 88
  • Error: "non-static method supportInvalidateOptionsMenu cannot be referenced from a static context" – IgorGanapolsky Aug 20 '13 at 22:45
  • 1
    @IgorGanapolsky, the notation I used above is just to show it is a method of `SherlockActivity`. You have to use it on an instance of that class, so typically inside your `SherlockActivity` activity you would just use `supportInvalidateOptionsMenu()` (or `this.supportInvalidateOptionsMenu()`). – Czechnology Aug 21 '13 at 01:10
  • 4
    If you're in a Fragment, it will be `getSherlockActivity().supportInvalidateOptionsMenu()` – karl Sep 19 '13 at 18:30
  • 1
    The answer of @candrews did not work for me when using ActionBarSherlock, but this one does. Thank you. – Hugo Matilla Feb 07 '14 at 17:42
30

If you are extending ActionBarActivity in your class then you just need this:

supportInvalidateOptionsMenu();
RicNjesh
  • 583
  • 10
  • 16
  • 1
    that did it for me. If you use the android.support.v7.app.ActionBar this is the right answer. – uldo Dec 18 '13 at 14:39
7

I dont think there is any need for compatibility library and so on, just do a simple

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

You dont need to call it before honeycomb since afaik, onPrepareOptionsMenu() called when menu button is pressed. It works for me.

urSus
  • 12,492
  • 12
  • 69
  • 89
1

Have you tried using a FragmentActivity from the Support Package instead of a normal activity? I believe the FramentActivity would then have the method that you need.

Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
  • Sadly, it does not. It extends `Activity`, so if you are targeting API 11+ you "have" it, but atlas, that's the original problem. – Jason Robinson Apr 03 '12 at 16:14
-1

I think I've got it... the answer was to create a new class:

public class wrapThree {
    public void invalidate(myActivity act) {
        act.invalidateOptionsMenu();
    }
}

and then call that method from myActivity if the API is 11+

At least this doesn't give errors on API < 11... still have to test it on API 11+

yuttadhammo
  • 5,069
  • 6
  • 34
  • 45