Stack Overflow archive
0 score

Check If MenuItem is In ActionBar Overflow

score
0
question views
2.9K
license
CC BY-SA 3.0

You can use reflection. Put the following code in a class and then invoke Foo.isInOverflow(yourMenuItem);

java
protected static final String SUPPORTCLASS = "android.support.v7.internal.view.menu.MenuItemImpl";

protected static final String NATIVECLASS = "com.android.internal.view.menu.MenuItemImpl";

protected static Method sSupportIsActionButton;

protected static Method sNativeIsActionButton;

static {
    try {
        Class<?> MenuItemImpl = Class.forName(NATIVECLASS);
        sNativeIsActionButton = MenuItemImpl.getDeclaredMethod("isActionButton");
        sNativeIsActionButton.setAccessible(true);
    } catch (Exception ignored) {
    }
    try {
        Class<?> MenuItemImpl = Class.forName(SUPPORTCLASS);
        sSupportIsActionButton = MenuItemImpl.getDeclaredMethod("isActionButton");
        sSupportIsActionButton.setAccessible(true);
    } catch (Exception ignored) {
    }
}

// --------------------------------------------------------------------------------------------

/**
 * Check if an item is showing (not in the overflow menu).
 * 
 * @param item
 *            the MenuItem.
 * @return {@code true} if the MenuItem is visible on the ActionBar.
 */
public static boolean isActionButton(MenuItem item) {
    switch (item.getClass().getName()) {
    case SUPPORTCLASS:
        try {
            return (boolean) sSupportIsActionButton.invoke(item, (Object[]) null);
        } catch (Exception e) {
            // fall through
        }
    case NATIVECLASS:
        try {
            return (boolean) sNativeIsActionButton.invoke(item, (Object[]) null);
        } catch (Exception e) {
            // fall through
        }
    default:
        return true;
    }
}

/**
 * Check if an item is in the overflow menu.
 * 
 * @param item
 *            the MenuItem
 * @return {@code true} if the MenuItem is in the overflow menu.
 * @see #isActionButton(MenuItem)
 */
public static boolean isInOverflow(MenuItem item) {
    return !isActionButton(item);
}

Note: you need to add the following line to your proguard configuration file so reflection works in production builds:

java
-keep public class android.support.v7.internal.view.menu.** { *; }

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.