Search code examples
androidandroid-actionbarandroid-menuandroid-actionbar-compat

Show icons in Overflow Menu in Contextual Action Bar


I know how to show icons in the overflow menu of the ActionBar. This is what I use,

  @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {

            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (NoSuchMethodException e) {
                    Log.e("TAG", "onMenuOpened", e);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

But when I long-press on any item of my ListView the CAB starts. Now, when I open the overflow menu of the CAB, the menu doesn't have any icons. How can I do that?

Thanks in advance.


Solution

  • I waited for 2 days but didn't get any answer on this. So solved it myself.

    The idea is quite simple here. You need to create your own overflow item in the and the create a nested menu to show both the icon and the text.

    See the example code below,

    <item
            android:id="@+id/overflow"
            android:icon="@drawable/ic_overflow_white"
            android:orderInCategory="201"
            android:title="@string/overflow"
            app:showAsAction="always">
    
            <menu>
                <item
                    android:id="@+id/cab_menu_select_all"
                    android:icon="@drawable/ic_select_all_grey"
                    android:orderInCategory="100"
                    android:title="@string/cab_menu_select_all"
                    app:showAsAction="always|withText"></item>
            </menu>
        </item>
    

    The trick here is to create nested menus. You can add as many items as you want.