Today you need to add an item to a menu dynamically, first record the method as follows
@Override Public BooleanOncreateoptionsmenu (Menu menu) {menu.add (Menu.none, Menu_revet,0, R.string.revert). setenabled (true). SetIcon (R.drawable.ic_settings_schpwroff). Setshowasaction (menuitem.show_as_action_if _room); Menu.add (Menu.none, Menu_save,0, R.string.done). setenabled (true). SetIcon (R.drawable.ic_settings_schpwroff). Setshowasaction (menuitem.show_as_action_if _room); return Super. Oncreateoptionsmenu (menu); }
Here are a few of the methods that we briefly introduce
Setenable: This is set MenuItem clickable state, set to false, will show Gray
SetIcon: Set icon
Setshowasaction: Set Menu display Location
Now let's focus on the last method-add
There are four parameters in this method, each of which has the meaning of
The group ID parameter of the first int type, which represents the concept of groups, allows you to group several menu items into groups to better manage your menu buttons in a group way. It corresponds to the method
int i = item.getgroupid ();
The item ID parameter of the second int type, which represents the project number. This parameter is important, and an item ID corresponds to an option in the menu. Use this item ID to determine which option you are using when using the menu later. It corresponds
int id = item.getitemid ();
The order ID parameter of the third int type, which represents the order in which the menu items are displayed. The default is 0, which means that the order in which the menus are displayed is displayed in the order in which they appear. If the number of two positions is the same, then the first definition of the Pat front. Furthermore, GroupID does not affect the order of arrangement.
The title parameter of the fourth string type, which represents the text displayed in the option.
Let's take a look at the next example
Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); Menu.add ("Hah"). SetIcon (R.drawable.abc_ab_bottom_solid_dark_holo). Setshowasaction (Menuitem.show_as_action_always); Menu.add ("Heihei"). SetEnabled (true). SetIcon (R.drawable.abc_ab_bottom_solid_dark_holo). Setshowasaction (Menuitem.show_as_action_always); Menu.add (1, one, 0, "1-1"). SetEnabled (false); Menu.add (1, 12, 0, "1-2"); Menu.add (1, 13, 2, "1-3"); Menu.add (2, 11, 3, "2-1"); Menu.add (2, 12, 4, "2-2"); return true; }
The results are as follows
menu-code addition and add method parameter meaning