Menu for Android development: OptionMenu (option Menu), ContextMenu (context Menu), SubMenu (sub Menu)

Source: Internet
Author: User

Menu for Android development: OptionMenu (option Menu), ContextMenu (context Menu), SubMenu (sub Menu)


The menu concept is now very popular.
Windows, Mac, Desktop Linux, and Java Swing all have visual menus.
I. Three menus on the Android platform
OptionMenu, ContextMenu, and SubMenu ).


1. Option Menu
Generally, the Menu button is provided on the mobile phone, corresponding to the Menu pop-up.


The main step is to rewrite the onCreateOptionMenu (Menu menu) method in the parent class of the Activity, and then add the Menu through the Menu add method,
Finally, when we click an option, override the onOptionsItemSelected (MenuItem item) method to implement the click event.


2. Context Menu
Context menu is a menu related to the current environment (user interface, a process.
For example, for the file manager, some addition, deletion, modification, and query can be placed in the ContextMenu. In fact, it implements a menu that is popped up after a user clicks.


3. SubMenu
Sub-menus, in terms of concept, can be said to belong to more types.

2. Understand Android menus
Menus are an indispensable part of many apps, especially in Android. All mobile phones equipped with Android systems even have a Menu key. This shows the particularity of menus in Android programs. The Android SDK provides the following menus:


Option menu: The most common menu. It is called option menu in android.
Sub-menu: Click sub-menu in android to display sub-menu items in the floating window. Sub-menus do not support nesting. That is, sub-menus cannot include any other sub-menus.
Context Menu: the menu that appears after the View Control in android. In windows, right-click the menu that appears, that is, the context menu.
Icon menu: this is a simple menu item with an icon. Note that icons cannot be displayed for sub-menu items, context menu items, and extended menu items.
Select menu (alternative menu ~~)
Extended menu: up to six menu items can be displayed in the option menu. If more than six menu items are displayed, the system replaces 6th menu items with a sub menu named "more, all menu items that cannot be displayed are used as sub-menu items of the "more" menu.


The Android SDK provides the following menus:


Option menu: The most common menu. It is called option menu in android.
Sub-menu: Click sub-menu in android to display sub-menu items in the floating window. Sub-menus do not support nesting. That is, sub-menus cannot include any other sub-menus.
Context Menu: the menu that appears after the View Control in android. In windows, right-click the menu that appears, that is, the context menu.
Icon menu: this is a simple menu item with an icon. Note that icons cannot be displayed for sub-menu items, context menu items, and extended menu items.
Select a menu (alternative menu): rarely used. (I found an article online, but I don't understand it. It's a strange feeling .)
Extended menu: up to six menu items can be displayed in the option menu. If more than six menu items are displayed, the system replaces 6th menu items with a sub menu named "more, all menu items that cannot be displayed are used as sub-menu items of the "more" menu.


The android. view. Menu interface represents a Menu. android uses it to manage various Menu items.
Note that we generally do not create a menu by ourselves, because each Activity comes with one by default. What we need to do is add a menu item for it and respond to the Click Event of the menu item.
Android. view. MenuItem indicates each menu item, and android. view. SubMenu indicates the sub menu. The relationship between the three can be used to represent


Each activity contains a Menu. A Menu can contain multiple Menu items and multiple sub-menus. A sub-Menu is actually a Menu (because it implements the Menu interface ), therefore, a sub-menu can contain multiple menu items.
SubMenu inherits the addSubMenu () method of Menu, but a runtime error is thrown during the call.
OnCreateOptionsMenu () and OnOptionsMenuSelected () are two callback methods provided in the activity for creating menu items and clicking the response menu items.




3. Three methods for responding to OptionMenu
1. Override the onOptionsItemSelected (MenuItem) callback method of the activity class. Every time a single menu item is clicked, android will call this method and pass in the clicked menu item.
Publicboolean onOptionsItemSelected (MenuItem item ){
Switch (item. getItemId ()){
// Respond to each menu item (by the menu item ID)
Case1:
// Do something here
Break;


Default:
// Submit the event to the parent class for processing.
Return super. onOptionsItemSelected (item );
}
// If the returned value is true, the event of the menu item is processed and does not need to be propagated.
Return true;
}

I think the "default" in this place is better.

 

2. Use listeners
Although the first method is recommended, android provides a listener similar to java swing to respond to the menu. The listener can be used in two steps:
// Step 1: Create a listener class
Class MyMenuItemClickListener implements OnMenuItemClickListener {
@ Override
Publicboolean onMenuItemClick (MenuItem item ){
// Do something here...
Returntrue; // finish handling
}
}


// Step 2: register the listener for the menu item
MenuItem. setOnMenuItemClickListener (new MyMenuItemClickListener ());
3. Use the Intent response menu
You can call the setIntent (Intent intent) method directly on MenuItem. In this way, android automatically calls startActivity (Intent) when the menu is clicked ).
However, I personally think it is better to manually call startActivity (Intent) directly in the onOptionsItemSelected case.


I personally prefer 1st methods. If there are many menu event codes, you can consider 2nd methods.
The problem with the 2nd method is that parameters may need to be passed to Listener.


Iv. Icon menu
// The Sub-menu item does not support displaying icons. This is meaningless, although no error is reported!
Menuitem1.setIcon (R. drawable. displaysettings );

// But the sub-menu itself supports icons
SubMenu. setIcon (R. drawable. settings );
There can be an icon in front of the menu. In the code below, the usage is not demonstrated.


5. Context Menu
The biggest difference between context Menu and Options Menu is that the owner of Options Menu is Activity, and the owner of context Menu is View in Activity.
Each Activity has only one Options Menu, which serves the whole Activity.
A single Activity usually has multiple views, not every View has a context menu, which needs to be explicitly specified through registerForContextMenu (View.


Although the context menu owner is View, the context menu is generated through the onCreateContextMenu (ContextMenu menu, View v, ContextMenu. ContextMenuInfo menuInfo) method in the Activity,
This method is similar to the onCreateOptionsMenu (Menu) method that generates the Options menu.
The difference between the two is that onCreateOptionsMenu is called only when the user presses the "Menu" key for the first time, while onCreateContextMenu is called every time the user presses the View for a long time, in addition, the context menu must be registered for the View.


Another important note is ContextMenuInfo. The object of this class is passed into the onCreateContextMenu (ContextMenu menu, View v, ContextMenu. ContextMenuInfo menuInfo) method. What is its usage?
Sometimes, the View element needs to pass some information to the context menu, such as the ID of the DB record corresponding to the View, which requires ContextMenuInfo.
The getContextMenuInfo () method must be rewritten for the View that needs to pass additional information. A ContextMenuInfo implementation Class Object with data is returned.


Three steps for how to create and respond to the context menu


1. register the context menu for a view in the onCreate (...) method of activity.


2. Generate the context menu in onCreateContextMenuInfo.


3. Respond to the context menu item in onContextItemSelected.


Vi. Sample Code
It should be noted that, Option Menu, left-click Menu or right-click Menu button to bring up the Menu.
Context Menu, long press View to bring up the Menu.


OptionMenu code
Package cn. fansunion. menu; import cn. fansunion. r; import android. app. activity; import android. OS. bundle; import android. view. menu; import android. view. menuItem; import android. view. subMenu; import android. widget. toast;/*** ①: directly overwrite the public boolean onCreateOptionsMenu (Menu menu) {code ......}, * This method should be noted that if it is overwritten, it will only be created once. That is to say, the option menu will only be instantiated once, then it will not be called * ②: Call the add () method in the Menu to add each Menu option, add (groupId, itemId, order, titleRes) group: * option group number, generally, if it is set to 0, it will be OK. itenId: Option Id is very important. order: order. Generally, if it is set to 0, titelRes: Option title name * ③: when we click an option, override the onOptionsItemSelected (MenuItem item) method to implement the click event. */public class OptionMenuActivity extends Activity {// click the constant Idprivate static final int MENU_ONE = 1 in the menu option; private static final int MENU_TWO = 2; private static final int MENU_THREE = 3; private int MENU_SUB = 11; private static final int GROUP_ZERO = 0; public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. option_menu);}/*** @ param group *: Option group number. Generally, if it is set to 0, OK * @ param itenId *: option Id is very important * @ param order *: order. Generally, set 0. * @ param titelRes *: Option title name */public boolean onCreateOptionsMenu (Menu menu) {menu. add (GROUP_ZERO, MENU_ONE, GROUP_ZERO, Xiao Lei); // a menu can include multiple sub-menus SubMenu = menu. addSubMenu (GROUP_ZERO, MENU_SUB, GROUP_ZERO, Xiao Lei interest); subMenu. add (GROUP_ZERO, MENU_TWO, GROUP_ZERO, Internet technology); subMenu. add (GROUP_ZERO, MENU_THREE, GROUP_ZERO, Investment and Financial Management); return true;}/***** @ param item *. getItemId () Get the clicked Id */public boolean onOptionsItemSelected (MenuItem item) {switch (item. getItemId () {case MENU_ONE: Toast. makeText (this, you click Menu1, Toast. LENGTH_LONG ). show (); break; case MENU_TWO: Toast. makeText (this, you click Menu2, Toast. LENGTH_LONG ). show (); break; case MENU_THREE: Toast. makeText (this, you click Menu3, Toast. LENGTH_LONG ). show (); break; default: return super. onOptionsItemSelected (item);} return true ;}}


Layout file layout
Option_menu.xml
   
       
       
  
   



ContextMenu code
Package cn. fansunion. menu; import cn. fansunion. r; import android. app. activity; import android. OS. bundle; import android. view. contextMenu; import android. view. contextMenu. contextMenuInfo; import android. view. menuItem; import android. view. view; import android. widget. textView; import android. widget. toast; public class ContextMenuActivity extends Activity {private static final int GROUP = 0; private static final int MENU_ONE = 1; private static final int MENU_TWO = 2; private static final int MENU_THREE = 3; private TextView contextView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. context_menu); contextView = (TextView) this. findViewById (R. id. contextMenu); registerForContextMenu (contextView);} @ Override public void onCreateContextMenu (ContextMenu menu, View v, ContextMenuInfo menuInfo) {super. onCreateContextMenu (menu, v, menuInfo); menu. add (GROUP, MENU_ONE, 0, Xiao Lei FansUnion); menu. add (GROUP, MENU_TWO, 0, Internet technology); menu. add (GROUP, MENU_THREE, 0, Investment and Financial Management) ;}@ Override public boolean onContextItemSelected (MenuItem item) {switch (item. getItemId () {case MENU_ONE: Toast. makeText (this, you click Menu1, Toast. LENGTH_LONG ). show (); contextView. setText (you click Menu1); break; case MENU_TWO: Toast. makeText (this, you click Menu2, Toast. LENGTH_LONG ). show (); contextView. setText (you click Menu2); break; case MENU_THREE: Toast. makeText (this, you click Menu3, Toast. LENGTH_LONG ). show (); contextView. setText (you click Menu3); break;} return true ;}}




Layout
Context_menu.xml
 
  
    
  
 


Note: This article mainly simplifies and optimizes the text and code based on the reference materials in the following three places and is transformed.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.