we have started with “How to change the Backgound and Text color of AppCompat Light DarkActionBar Theme” . Sometimes you want to add icons in the android app overflow menu. Here is the final result:
Sometimes it is not enough to define the icon in you activity xml file located in res/menu:
1 2 3 4 5 6 |
<item> ... android:title="@string/action_profil" android:icon="@drawable/ic_action_person" ... </item> |
In some cases this will not have any effect to display the icon beside the item title.
Let we start to download the Action Bar Icon Pack from the following Android download link: https://developer.android.com/design/downloads/index.html#action-bar-icon-pack.
You can also create your own icons, just respect the different devices display format:
- drawable-mdpi: 32 x 32 px
- drawable-hdpi : 48 x 48 px
- drawable-xhdpi 64 x 64 px
- drawable-xxhdpi 96 x 96 px
After dowloading the zip file, just unziped and search for the “Action Bar Icons” folder. You have to choice which icons folder you want to use in your theme. You have two folders: the Holo Light and the Holo Dark .
Next step is to search for the icon that you want to use for the overflow title. In our example we will use the “06_social_add_person” icons.
Just copy the different folders inside your project workspace (/res folder).
Now you have all icons available:
Your activity xml should now have following entry’s:
1 2 3 4 5 6 |
<item android:id="@+id/action_profil" android:orderInCategory="0" android:title="@string/action_profil" android:icon="@drawable/ic_action_person" app:showAsAction="never"/> |
You have to specify the title in /res/values/strings.xml :
1 |
<string name="action_profil">Profil</string> |
The orderInCategory
is just to ensure the item sequence in the overflow menu. We start the profile menu with the “0” position.
So, lets add some standard java code to be able to display the menu icons. Add followig code to your Activity located in /src/YourActivity.java
@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){ //write in the LogCat Log.e(TAG, "onMenuOpened", e); } catch(Exception e){ throw new RuntimeException(e); } } } return super.onMenuOpened(featureId, menu); }
Eclipse ADT will suggest to import the necessary classes, in this case:
import java.lang.reflect.Method; import android.view.Window; import android.util.Log;
That’s all !