In the Android4.0 system, creating menu menus, using the SetIcon method to add icons to the menu is not valid, the icon is not shown, 2.3 system can be displayed. The root cause of this problem lies in the 4.0 system, the source of the menu related to the Menubuilder has been changed, the part of the source code is as follows:
public class menubuilder implements menu {... private boolean moptionaliconsvisible = false Span style= "color: #000000;" >;.... void setoptionaliconsvisible (boolean " Span style= "color: #000000;" > visible) {moptionaliconsvisible = visible; boolean getoptionaliconsvisible () { return moptionaliconsvisible; }...}
In the above code, the moptionaliconsvisible member initial value defaults to False, which is why the menu setting icon has no effect; As long as we create the menu by calling the Setoptionaliconsvisible method to set Moptionaliconsvisible to True, then the problem is that to invoke the method, you need to create the Menubuilder object, but We are unable to create the Menubuilder object in the developed application (Menubuilder is the framework class inside the system).
It's time to consider reflection, call the Setoptionaliconsvisible method by reflection when the code runs to create the menu, set Moptionaliconsvisible to True, and then add an icon to the menu, This allows you to display the added icon in the menu.
@Override Public BooleanOncreateoptionsmenu (Menu menu) {seticonenable (menu,true);//call this implementation to show iconMenu.add ("Add Notes"). SetIcon (R.drawable.add); Menu.add ("Notes List"). SetIcon (R.drawable.list); Menu.add ("Classification Management"). SetIcon (R.drawable.category); Menu.add ("Official website"). SetIcon (R.drawable.web); Menu.add (On). SetIcon (R.drawable.about); Menu.add (Exit). SetIcon (R.drawable.exit); return Super. Oncreateoptionsmenu (menu);}//when enable is true, the menu add icon is valid and the enable is false when it is not valid. 4.0 system default is not validPrivate voidSeticonenable (Menu menu,Booleanenable) { Try{Class<?> clazz = Class.forName ("Com.android.internal.view.menu.MenuBuilder"); Method m= Clazz.getdeclaredmethod ("Setoptionaliconsvisible",Boolean.class); M.setaccessible (true);//Menubuilder Implement the menu interface, when creating menus, the passed-in menu is actually the Menubuilder object (Java polymorphic feature) M.invoke (menu, enable); } Catch(Exception e) {e.printstacktrace (); }}
Resolves an issue where the Optionsmenu menu does not display icon icons in Android 4.0 or later