How To show icons in Overflow menu in ActionBar
I know it's not possible using the native API. Is there a workaround to implement that kind of view?
The previously posted answer is OK, generally speaking. But it basically removes the default behaviour of the Overflow menu. Things like how many icons can be displayed on different screen-sizes and then they dropped off into the overflow menu when they can't be displayed. By doing the above you remove a lot of important functionality.
A better method would be to tell the overflow menu to display the icons directly. You can do this by adding the following code to your Activity.
@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);
}
In your menu xml, use the following syntax to nest menu, you will start getting the menu with icons
<item
android:id="@+id/empty"
android:icon="@drawable/ic_action_overflow"
android:orderInCategory="101"
android:showAsAction="always">
<menu>
<item
android:id="@+id/action_show_ir_list"
android:icon="@drawable/ic_menu_friendslist"
android:showAsAction="always|withText"
android:title="List"/>
</menu>
</item>
Tried this based on the previous answers and it works fine, at least with more recent versions of the support library (25.1):
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
if(menu instanceof MenuBuilder){
MenuBuilder m = (MenuBuilder) menu;
//noinspection RestrictedApi
m.setOptionalIconsVisible(true);
}
return true;
}
You can make use of SpannableString
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tab, menu);
MenuItem item = menu.findItem(R.id.action_login);
SpannableStringBuilder builder = new SpannableStringBuilder("* Login");
// replace "*" with icon
builder.setSpan(new ImageSpan(this, R.drawable.login_icon), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
item.setTitle(builder);
}