Search code examples
androidandroid-appcompatandroid-menuappcompatactivity

What's the correct import of Menu and MenuItem when using appCompat in Android?


I previously used ActionBarSherlock, but now I'm moving all my apps to the Material Theme using appCompat. I'm getting an UnsupportedOperationException with my code below:

 MenuItem num = (MenuItem) menu.findItem(R.id.num);

        num.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem menuItem) {
                //wow
            }

I'm getting an error of:

java.lang.UnsupportedOperationException: This is not supported, use MenuItemCompat.setOnActionExpandListener()
            at android.support.v7.internal.view.menu.MenuItemImpl.setOnActionExpandListener(MenuItemImpl.java:740)

So what should I do in this case? Should my Menu and MenuItems import from some other package? Or do I just need to use a different all together with MenuCompat and MenuItemCompat. Thanks


Solution

  • The method setOnActionExpandListener was added only in API level 14. Therefore you can't use it safely as it does not exist in API levels lower than 14.

    In your case, as suggested by the error message, you should use MenuItemCompat.setOnActionExpandListener().