Android Options Menu and context menu parsing

Source: Internet
Author: User

Options Menu
Creating the Options Menu

The activity class's Oncreateoptionmenu event method is used to create the Options menu, which is defined as follows:

@Overridepublic boolean Oncreateoptionsmenu (Menu menu) {return Super.oncreateoptionsmenu (menu);}


It is generally necessary to place the code that creates the Options menu in the Oncreateoptionmenu method. You can add a menu of options by using the Menu.add method. The


There are 4 overloaded forms of the method, defined as follows:


Public MenuItem Add (charsequence title);
Public MenuItem Add (int titleres);
Public MenuItem Add (int groupId, int itemId, int order, int titleres);
Public MenuItem Add (int groupId, int itemId, int order, charsequence title);


    • The Add method has a maximum of 4 parameters, which have the following meanings:
    • GROUPID: The group ID of the menu item, which is typically used for menus with selection buttons. The parameter values can be negative integers, 0, and positive integers.
    • ITEMID: The ID of the currently added menu item. The parameter can be a negative integer, 0, and a positive integer.
    • Order: the menu display sequence. The Android system displays the menu item in ascending order from left to right, top to bottom, according to the value of the?? The parameter must be 0 and a positive integer and cannot be a negative integer.
    • Titleres and Title: The string resource ID or string of the menu item title.

The following code adds several options menus:

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {menu.add (1, 1, 1, "menu item 1"), Menu.add (1, 2, 2, "menu item 2"), Menu.add (1, 3 , 3, "menu item 3"), Menu.add (1, 4, 4, "menu item 4"), Menu.add (1, 5, 5, "menu item 5"), Menu.add (1, 6, 6, "menu item 6"); return true;}
effectFigure:


Options menu with an image

As can be seen from the Add method above, the method returns a MenuItem object that corresponds to a menu item for each MenuItem object. can be done by


The corresponding method of the MenuItem interface to set the content related to the menu item, for example, the image displayed on the


Menuitem.seticon method to add, the method is defined as follows:


The following code sets the image for the menu item:

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {seticonenable (menu, true);  Menu.add (1, 1, 1, "menu item 1"). SetIcon (R.DRAWABLE.B10); Menu.add (1, 2, 2, menu item 2). SetIcon (R.DRAWABLE.B14); return true;} private void Seticonenable (Menu menu, Boolean enable)      {          try           {              class<?> clazz = Class.forName (" Com.android.internal.view.menu.MenuBuilder ");              Method m = Clazz.getdeclaredmethod ("setoptionaliconsvisible", boolean.class);              M.setaccessible (true);               M.invoke (menu, enable);                        } catch (Exception e)           {              e.printstacktrace ();}}  }

It is noteworthy here that Android 4.0 after calling the SetIcon method through the MenuItem object is unable to set the icon for the menu item, in Android2.0


Can be displayed, so you want to set the icon through the SetIcon method, you can set the Setoptionaliconsvisible method by reflection


Moptionaliconsvisible is true. For more information, please refer to the " troubleshooting Menu" in android4.0 system to add icon invalid.






Associated activity

Association of activity We can use the Menuitem.setintent method to specify a intent object. The Setintent method is defined as follows:

Public MenuItem setintent (Intent Intent);

When you associate an activity with a menu item, you click the menu item and the system calls the StartActivity method to display the activity associated with the menu item, the following generation


Code to specify an activity by calling the Setintent method:

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {seticonenable (menu, true);  Menu.add (1, 1, 1, "menu item 1"). SetIcon (R.DRAWABLE.B10). Setintent (New Intent (Mainactivity.this, Secondactivity.class)); return true;} private void Seticonenable (Menu menu, Boolean enable)      {          try           {              class<?> clazz = Class.forName (" Com.android.internal.view.menu.MenuBuilder ");              Method m = Clazz.getdeclaredmethod ("setoptionaliconsvisible", boolean.class);              M.setaccessible (true);               M.invoke (menu, enable);                        } catch (Exception e)           {              e.printstacktrace ();}}  }




Click Action on the Response menu

You can set a click event for a menu item by calling the Menuitem.setonmenuitemclicklistener method, which has a


For Onmenuitemclicklistener type parameters, the Click event class that handles the menu item must implement the Setonmenuitemclicklistener interface, the following generation


The code sets the Click event:


public class Mainactivity extends Activity implements onmenuitemclicklistener{@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {seticonenable (menu, true); MenuItem item = menu.add (1, 1, 1, "menu item 1"). SetIcon (R.DRAWABLE.B10); Item.setonmenuitemclicklistener (this); return true;} @Overridepublic boolean Onmenuitemclick (MenuItem item) {if (Item.getitemid () ==1) {Toast.maketext (Mainactivity.this, " Click on menu item 1 ", Toast.length_short). Show ();} return false;} private void Seticonenable (Menu menu, Boolean enable) {try {class<?> clazz = Class.forName (" Com.android.internal.view.menu.MenuBuilder "); Method m = Clazz.getdeclaredmethod ("setoptionaliconsvisible", Boolean.class); m.setaccessible (true); M.invoke (menu, enable);} catch (Exception e) {e.printstacktrace ();}}}

:




In addition to setting click events for menu items, you can also use the Activity class's onoptionsitemselected and onmenuitemselected methods to respond to dishes


Single-click events, the two methods are defined as follows:

<pre name= "code" class= "Java" >public boolean onoptionsitemselected (MenuItem Item);p Ublic Boolean onmenuitemselected (int featureid, MenuItem item);


use of onoptionsitemselected:

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {seticonenable (menu, true); MenuItem item = menu.add (1, 1, 1, "menu item 1"). SetIcon (R.DRAWABLE.B10); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem item) {if (item.getitemid () = = 1) {Toast.maketext ( Mainactivity.this, "Clicked on menu item 1", Toast.length_short). Show (); return true;} private void Seticonenable (Menu menu, Boolean enable) {try {class<?> clazz = Class.forName (" Com.android.internal.view.menu.MenuBuilder "); Method m = Clazz.getdeclaredmethod ("setoptionaliconsvisible", Boolean.class); m.setaccessible (true); M.invoke (menu, enable);} catch (Exception e) {e.printstacktrace ();}}}

use of the Onmenuitemselected method:

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {seticonenable (menu, true); MenuItem item = menu.add (1, 1, 1, "menu item 1"). SetIcon (R.DRAWABLE.B10); return true;} @Overridepublic boolean onmenuitemselected (int featureid, MenuItem item) {if (item.getitemid () = = 1) {Toast.maketext ( Mainactivity.this, "Clicked on menu item 1", Toast.length_short). Show (); return true;} private void Seticonenable (Menu menu, Boolean enable) {try {class<?> clazz = Class.forName (" Com.android.internal.view.menu.MenuBuilder "); Method m = Clazz.getdeclaredmethod ("setoptionaliconsvisible", Boolean.class); m.setaccessible (true); M.invoke (menu, enable);} catch (Exception e) {e.printstacktrace ();}}}

submenu with check boxes and option buttons

Traditional submenus are displayed in a hierarchical structure, while the submenus in Android are displayed in a pop-up fashion. That is, when you click a menu with a submenu


After a single item, the parent menu closes and the submenu is displayed on the screen.


The Menu.addsubmenu method is used to add a submenu, which has 4 overloaded forms, defined as follows:


Submenu Addsubmenu (final charsequence title); submenu Addsubmenu (final int titleres); submenu Addsubmenu (final int groupId, final int itemId, int order, final charsequence title); submenu Addsubmenu (int groupId, int itemId, int order, int titleres);

The Addsubmenu method and the Add method have the same number of method parameters as the type, but their return value type is different, and the Addsubmenu method returns


A submenu object, submenu is a submenu of the menu, you can add a submenu item by Submenu.add method, the following code sets two sub-


menu, each of the two menu types is defined:

public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {seticonenable (menu, true); Submenu submenu = Menu.addsubmenu (1, 1, 2, "menu item"); Submenu.seticon (R.DRAWABLE.B10); Submenu.setheadericon ( R.DRAWABLE.B18); MenuItem menuItem1 = Submenu.add (1, 2, 2, "submenu 1");/* * Set submenu 1 to check box type */menuitem1.setcheckable (TRUE); MenuItem menuItem2 = Submenu.add (2, 3, 3, "submenu 2"),/* * Set to option button */submenu.setgroupcheckable (2, True, true); return true;} @Overridepublic boolean onmenuitemselected (int featureid, MenuItem item) {if (item.getitemid () = = 2) {Toast.maketext ( Mainactivity.this, "clicked on sub-menu item 1", Toast.length_short). Show (); else if (Item.getitemid () ==3) {Toast.maketext (Mainactivity.this, "clicked Sub-menu item 2", Toast.length_short). Show (); return true;} private void Seticonenable (Menu menu, Boolean enable) {try {class<?> clazz = Class.forName ("Com.androId.internal.view.menu.MenuBuilder "); Method m = Clazz.getdeclaredmethod ("setoptionaliconsvisible", Boolean.class); m.setaccessible (true); M.invoke (menu, enable);} catch (Exception e) {e.printstacktrace ();}}}




Context Menu


Context menus can be associated with any view object, such as TextView, Eidttext, button, and so on, which can be associated with a context menu. On


The following menus are similar in appearance and submenus, and are also categorized as menu headers and menu items.


To create a context menu, you need to override the Activity.oncreatecontextmenu method, which is defined as follows:


<pre name= "code" class= "java" >public void Oncreatecontextmenu (ContextMenu menu, View v,contextmenuinfo menuinfo)

You can use the Contextmenu.setheadertitle and Contextmenu.setheadericon methods to set the caption and image of the context menu header. up and down

The Text menu item cannot have an image, but you can bring a check box and an option button. The following code defines the context menu, which can be displayed by long-pressing the text:

public class Mainactivity extends Activity {private TextView tv_contextmenu; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); InitView ();} private void Initview () {Tv_contextmenu = (TextView) Findviewbyid (r.id.tv_contextmenu);// Register context menu Registerforcontextmenu (Tv_contextmenu);} @Overridepublic boolean onmenuitemselected (int featureid, MenuItem item) {if (item.getitemid () = = 1) {Toast.maketext ( Mainactivity.this, "Clicked on menu item 1", Toast.length_short). Show (); else if (item.getitemid () = = 2) {Toast.maketext (Mainactivity.this, "clicked menu item 2", Toast.length_short). Show ();} else if (item . Getitemid () = = 3) {Toast.maketext (Mainactivity.this, "clicked on submenu", Toast.length_short). Show ();} else if (Item.getitemid () = = 4) {Toast.maketext (Mainactivity.this, "clicked on sub-menu item 1", Toast.length_short). Show ();} else if (item.getitemid () = = 5) {Toast . Maketext (Mainactivity.this, "clicked on sub-menu item 2", Toast.length_short). Show (); return true;} @Overridepublic void onCreatecontextmenu (ContextMenu menu, View v,contextmenuinfo menuinfo) {super.oncreatecontextmenu (menu, V, menuinfo); Menu.setheadertitle ("context menu"); Menu.setheadericon (r.drawable.b13); menu.add (0, 1, menu.none, "menu item 1"); Menu.add (2, 2, Menu.none, "menu item 2"); submenu Sub = Menu.addsubmenu (1, 3, Menu.none, "submenu"), Sub.add (1, 4, 4, "Sub-menu item 1"), Sub.add (1, 5, 5, "submenu item 2");}}









--------------------------------------------------------------------------------------------------------------- ----------------------------------------

Reprint Please specify source:http://blog.csdn.net/hai_qing_xu_kong/article/details/47439377#t6 Emotional control


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Options Menu and context menu parsing

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.