I want to show a overflow menu in toolbar(AppCompat-v7:22.1.1), below is my menu_main.xml.
<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"
tools:context=".MainActivity">
<item
android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@mipmap/ic_menu_search"
android:orderInCategory="100"
android:actionViewClass="android.widget.SearchView"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/menu_group_chat"
android:title="@string/menu_group_chat"
android:icon="@mipmap/ic_menu_groupchat" />
<item
android:id="@+id/menu_add_friend"
android:title="@string/menu_add_friend"
android:icon="@mipmap/ic_menu_add_friend" />
After running my app, the icon of menu item is not displayed, then I tried this solution, add an override method onMenuOpened()
in my Activty(extends from AppCompatActivity
),
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if(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 (Exception e) {
e.printStackTrace();
}
}
}
return super.onMenuOpened(featureId, menu);
}
But after running this demo, I find that the icon is still not displayed.
From this reported issue, I know that AppCompatActivity.onMenuOpened
is not called any more in 22.x, but it's odd that when I click the hardware menu key in Genymotion, the menu appear at the bottom and with the icon,
after closing the menu, I click the overflow button in the toolbar again, these icons in menu appear,
how strange it is! Why this happens?
For the AppCompactActivity you can put this check on the onPrepareOptionsPanel() instead.
@Override
protected boolean onPrepareOptionsPanel(View view, Menu menu) {
if (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 (Exception e) {
Log.e(getClass().getSimpleName(), "onMenuOpened...unable to set icons for overflow menu", e);
}
}
}
return super.onPrepareOptionsPanel(view, menu);
}
this is works for me
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
//this section is the one that allows to visualize the icon
if(menu instanceof MenuBuilder){
MenuBuilder m = (MenuBuilder) menu;
//noinspection RestrictedApi
m.setOptionalIconsVisible(true);
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With