Icons on a context menu are not showing?

1.1k views Asked by At

When i long click on a recyclerview item the context menu shows but only the text, not the associated icons, here's the code:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <item
        android:id="@+id/bookmark"
        android:orderInCategory="1"
        android:title="@string/bookmarked_ayah"
        android:icon="@drawable/ic_bookmark" />
    <item
        android:id="@+id/fbshare"
        android:orderInCategory="2"
        android:title="@string/fb_share"
        android:icon="@drawable/ic_facebookshare" />
    <item
        android:id="@+id/saveayah"
        android:orderInCategory="3"
        android:title="@string/save_ayah"
        android:icon="@drawable/ic_save" />
    </menu>

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.ayah_saving_actionbar_items,menu);

        return true;
    }
1

There are 1 answers

1
Misha Akopov On BEST ANSWER

If you're running your code on Android 3.0+, the icons in the menu are not shown by design. This is a design decision by Google.

But if you really want to show icons, you can use the code:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    try {
        Field field = menu.getClass().getDeclaredField("mOptionalIconsVisible");
        field.setAccessible(true);
        field.setBoolean(menu, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return super.onPrepareOptionsMenu(menu);
}

It uses reflection and sets the icons visible. I tested and here is the result:

enter image description here