) Options menu and context menu

Source: Internet
Author: User

The activity noteslist is analyzed, and the intent mechanism is analyzed. This article will continue the previous work, and introduce the menu mechanism (especially the dynamic menu mechanism) of Android with noteslist as an example ).


Android provides three menu types: Options menu, context menu, and sub menu.

The options menu is displayed by pressing the Home key. The context menu needs to be displayed after pressing the top 2 S button on The View. Both menus can be added to sub-menus. Sub-menus cannot be nested. The options menu can display up to six menu options at the bottom of the screen, which is called the icon menu. The icon menu cannot have the checkable option. More than 6 menu items are called expanded menu. Options menu is generated by oncreateoptionsmenu of the activity. This function is called only when the menu is generated for the first time. Any idea of changing the Options menu can only be implemented in onprepareoptionsmenu. This function will be called before the menu is displayed. Onoptionsitemselected is used to process selected menu items.

Context menu is bound to a specific view. In activity, registerforcontextmenu is used to register context menu for a view. Before the context menu is displayed, oncreatecontextmenu is called to generate the menu. Oncontextitemselected is used to process selected menu items.

Android also provides the function of grouping menu items. You can divide menu items with similar functions into the same group. In this way, you can set menu properties by calling setgroupcheckable, setgroupenabled, and setgroupvisible, you do not need to set it separately.

Options Menu

The options menu and context menu are used in notepad. First, let's look at the oncreateoptionsmenu function that generates the Options menu.

Menu. Add (0, menu_item_insert, 0, R. String. menu_insert)
. Setshortcut ('3', 'A ')
. Seticon (Android. R. drawable. ic_menu_add );

This is a standard method for inserting a menu item. The menu item ID is menu_item_insert.

The following code is interesting:

Intent intent = new intent (null, getintent (). getdata ());
Intent. addcategory (intent. category_alternative );
Menu. addintentoptions (menu. category_alternative, 0, 0,
New componentname (this, noteslist. Class), null, intent, 0, null );

What is the purpose of this? In fact, this is a dynamic menu technology (also a bit like plug-in mechanism). If an activity, its type is "android. intent. category. alternative ", the data is" Vnd. android. cursor. DIR/vnd. google. note, the system will add a menu item for this activity. View in androidmanfest. xml and find that no activity meets the conditions, so this code does not dynamically add any menu item.

To verify the above analysis, we can make an experiment and modify it in androidmanfest. XML to see if a single menu item is generated dynamically.

Lab 1 

First, create a new activity as the target activity named helloandroid. There is no function, that is, to display an interface.

Public class helloandroid extends activity {
@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
This. setcontentview (R. layout. Main );

The XML file corresponding to the layout interface is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content" Android: Id = "@ + ID/textview01"/>

<Button Android: Id = "@ + ID/button01" Android: layout_height = "wrap_content" Android: layout_width = "fill_parent" Android: TEXT = "@ string/txtinfo"> </button>

Then modify androidmanfest. xml and add the following configuration to make helloandroid meet the preceding two conditions:

<Activity Android: Name = "helloandroid" Android: Label = "@ string/txtinfo">
<Action Android: Name = "com. Android. notepad. Action. hello_test"/>
<Category Android: Name = "android. Intent. Category. Alternative"/>
<Data Android: mimetype = "Vnd. Android. cursor. DIR/vnd. Google. Note"/>

Okay. Run it and try again. Well, there is still no dynamic menu item to add!

What's going on? After checking the code, I found that it was originally a ghost of onprepareoptionsmenu! This function runs after oncreateoptionsmenu. In the following code. category_alternative points to the same group, so the menu items set in oncreateoptionsmenu are overwritten, because onprepareoptionsmenu does not give the menu. category_alternative has a new value, so menu. category_alternative is null.

Intent intent = new intent (null, Uri );
Intent. addcategory (intent. category_alternative );
Menu. addintentoptions (menu. category_alternative, 0, 0, null, specifics, intent, 0, items );

Okay, now let's comment out the above sentences. Of course, you can also leave them uncommented. In oncreateoptionsmenu, change the groupid number, that is, the menu. change category_alternative to menu. first, do the rest, but do not change it to menu. none.

Menu. Add (0, menu_item_insert, 0, R. String. menu_insert)
. Setshortcut ('3', 'A ')
. Seticon (Android. R. drawable. ic_menu_add );

The menu to add. Because menu. None is also 0

After running, you can see the dynamic menu!


The preceding options menu is generated when no log list is selected on the noteslist interface. If a log is selected first, click "menu ", the generated options menu is as follows:


Alas, two menu items "Edit note" and "Edit title" are added dynamically. How does one add them dynamically? This is the credit of onprepareoptionsmenu.

Uri uri = contenturis. withappendedid (getintent (). getdata (), getselecteditemid ());

First obtain the selected log (if not selected, the URI is empty)

Intent [] specifics = new intent [1];
Specifics [0] = new intent (intent. action_edit, Uri );
Menuitem [] items = new menuitem [1];

Create an intent for the selected log. The operation type is intent.Action_editThe data is the URI of the selected log. A "Edit note" menu item is created for the selected log.

Intent intent = new intent (null, Uri );
Intent. addcategory (intent. category_alternative );
Menu. addintentoptions (menu. category_alternative, 0, 0, null, specifics, intent, 0,
Items );

These statements are similar to those in the oncreateoptionsmenu function. They are used to dynamically add menu items. If an activity is of the "android. intent. category. alternative ", the data is" Vnd. android. cursor. item/vnd. google. note, the system will add a menu item for this activity. View in androidmanfest. xml and find that the activity titleeditor meets the conditions, so the system dynamically adds a menu item "Edit title" for the activity titleeditor ".

Else {
Menu. removegroup (menu. category_alternative );

If the log list is empty, the menu is deleted from the menu.Category_alternativeOnly the "add note" menu items are left.

Processing"Select menu items"Event 

The process of selecting an event from a menu item is very simple. onoptionsitemselected is used to complete the process. Here, only startactivity (NewIntent (intent.Action_insert, Getintent (). getdata (); the intent operation type is intent.Action_insertThe data is the URI of the log list, that is, "content: // com. Google. provider. notepad/Notes"

@ Override
Public Boolean onoptionsitemselected (menuitem item ){
Switch (item. getitemid ()){
Case menu_item_insert:
// Launch activity to insert a new item
Startactivity (new intent (intent. action_insert, getintent (). getdata ()));
Return true;
Return super. onoptionsitemselected (item );

Context Menu

Next we will introduce another menu-context menu, which is implemented by reloading the oncreatecontextmenu function.

First, confirm that a log in the log list has been selected. If not selected, return directly. Cursor points to the selected log item.

Cursor cursor = (cursor) getlistadapter (). getitem (info. position );
If (cursor = NULL ){
// For some reason the requested item isn't available, do nothing

Then, set the context menu title to the log title

// Setup the menu Header
Menu. setheadertitle (cursor. getstring (column_index_title ));

Add a menu item for the context menu.

// Add a menu item to Delete the Note
Menu. Add (0, menu_item_delete, 0, R. String. menu_delete );

The event processing for the selected context menu item is implemented by reloading oncontextitemselected.

Switch (item. getitemid ()){
Case menu_item_delete :{
// Delete the note that the context menu is
Uri noteuri = contenturis. withappendedid (getintent (). getdata (), info. ID );
Getcontentresolver (). Delete (noteuri, null, null );
Return true;
Return false;

To delete a log, call contenturis first. withappendedid (getintent (). getdata (), info. ID); to splice the URI of the log to be deleted. then getcontentresolver (). delete (noteuri, null, null); call the lower-level content provider to delete this log.

Lab 2 

To create a simple experiment, add a context menu item based on the above Code. First, add a context menu item to the oncreatecontextmenu function:

Menu. Add (0, menu_item_insert, 0, R. String. menu_insert );

Then add a processing procedure to the oncontextitemselected function:

Case menu_item_insert:
New alertdialog. Builder (this). seticon (R. drawable. app_notes)
. Settitle (R. String. app_name). setmessage (R. String. error_message). setpositivebutton (R. String. button_ OK, new onclicklistener (){

Public void onclick (dialoginterface dialog, int which ){
// Todo auto-generated method stub


}). Show ();
Return true;

The experiment results are as follows:

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.