Summary of how to use Android onCreateOptionsMenu
The use of "menu" is indispensable for any software. On Android, each activity is bundled with a menu. To define and use the menu, you must operate under the Activity and rewrite the two methods onCreateOptionsMenu and onOptionsItemSelected. As an example:
@Override public boolean onCreateOptionsMenu(Menu menu) { //Calling the base class method to call out the system menu (if any) (menu); (0, 1, 0, "restart").setIcon(); (0, 2, 0, "Game Guide").setIcon(); (0, 3, 0, "About the Game").setIcon(); (0, 4, 0, "I don't want to play anymore").setIcon(); //The return value is "true", which means that the menu is visible, that is, the menu is displayed return true; }
Take a look at the parameters in the method:
The first int type group ID parameter represents the group concept. You can group several menu items into a group to better manage your menu buttons in a group way. The methods that can be used are:
removeGroup(id) setGroupCheckable(id, checkable, exclusive) setGroupEnabled(id,boolean enabled) setGroupVisible(id,visible)
Personally, I think that when you need to display different menus in different occasions, using this parameter reasonably will more effectively handle the display of the menu. Otherwise, they are generally grouped.
The second int type item ID parameter represents the project number. This parameter is very important. An item ID corresponds to the options in a menu. When using the menu later, it depends on this item ID to determine which option you selected.
The third int type order ID parameter represents the display order of menu items. The default is 0, which means that the menu display order is displayed in the order of add.
The fourth String type title parameter indicates the text displayed in the option.
Let’s take a look at the setIcon method, which is to add icons to the menu and use resource files.
After designing the menu, continue to rewrite the onOptionsItemSelected method to respond to the menu. Sample code:
@Override public boolean onOptionsItemSelected(MenuItem item) { (item); switch(()){ case 1: //Processing code break; case 2: //Processing code break; case 3: //Processing code break; case 4: finish(); break; } return true; }
The above is a detailed introduction to the parameters of Android onCreateOptionsMenu. If you have any questions, please leave a message or go to the community of this site to communicate and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!