Reproduced) Android Menu details--Understanding the menu in Android (2012-11-25 18:52:30)
reproduced
Tags: gossip |
Category: Android Development Knowledge (reprint) |
Original reference: Http://www.cnblogs.com/qingblog/archive/2012/06/08/2541709.html
Android Menu Explanation--Understanding menu in AndroidPreface
Today saw the pro Android 3 menu in this chapter, the whole Android menu system has a further understanding, so take notes to share with you.
PS: Highly recommended "Pro Android 3", is the best I have seen so far the Android book, the Chinese version of "Proficient Android 2."
Understanding the Android menu
Menus are an integral part of many applications, especially in Android, where all Android-powered phones even have a "menu" key, which shows the specifics of menus in Android programs. The following menus are available from the Android SDK:
- Options Menu: The most general menu, Android call it option menu
- submenu: Clicking on the submenu in Android will pop up the hover window to display the submenu item. The submenu does not support nesting , which means that no more submenus can be included in the sub-menu.
- Context Menu: The menu that appears after long press the view control in Android, Windows right-click popup menu that is context menu
- Icon Menu: This is relatively simple, is a menu item with icon, it is necessary to note that the submenu items, context menu items, extended menu items cannot display the icon .
- Select menu (Alternative menu): With less, later introduced separately, this article first skip (actually I have not figured out O (≧v≦) o~~)
- Extended Menu: The Options menu can only display 6 menu items, more than 6, the 6th menu item will be replaced by a system called "more" sub-menu, the original display items are not displayed as a submenu item in the "More" menu. Such as:
The 6th menu item automatically changes to "more" click "More" to show other menu items
ANDROID3.0 also introduced a call Action bar, this article does not explain, we own Google.
The Android.view.Menu interface represents a menu that Android uses to manage various menu items. Note that we generally do not create the menu ourselves, because each activity has its own default, and what we do is to add a menu item to it and respond to the Click event of the menu item . Android.view.MenuItem represents each menu item and Android.view.SubMenu represents a submenu. The relationship between the three can be used to denote
As mentioned above, each activity contains a menu, a menu can contain multiple menu items and multiple submenus, the submenu is actually a menu (because it implements the menu interface), so the submenu can also contain multiple menu items. submenu inherits the menu's Addsubmenu () method, but it throws a run-time error when it is called. Oncreateoptionsmenu () and onoptionsmenuselected () are two callback methods available in activity that create a click of a menu item and respond to a menu item.
Create Options Menu
As mentioned earlier, the activity of Android has created a Android.view.Menu object for us in advance and provided a callback method Oncreateoptionsmenu (Menu menu) for us to initialize the contents of the menus. This method will only be executed when the option menu is displayed for the first time, and if you need to dynamically change the contents of the Options menu , useonPrepareOptionsMenu(Menu)
。
@Override
PublicbooleanOncreateoptionsmenu (Menu menu) {
//calling the parent class method to join the system menu
Although Android does not yet have a system menu, it is best to add it to a later version
Super. Oncreateoptionsmenu (menu);
//Add menu items (multiple ways)
1. Direct designation of headings
menu.add ("menu item 1");
2. Assigning headings through resources
menu.add (R.STRING.MENUITEM2);
3. Displays the group number, ID, sort number, title of the specified menu item
Menu.add (
1,//group number
Menu.first,//unique ID number
Menu.first,//Sort number
"menu item 3"); //Title
Returns true if you want the menu to be displayed
returntrue;
}
上面的代码演示了添加菜单项的3种方法,下面解释下第三种方法
Add (int groupId, int itemId, int order,charsequence title)。其中,第一个参数是组号,android中你可以给菜单分组,以便快速地操作同一组的菜单。第二个参数指定每个菜单项的唯一ID号,你可以自己指定,也可以让系统来自动分配,在响应菜单时你需要通过ID号来判断哪个菜单被点击了。因此常规的做法是定义一些ID常量,但在android中有更好的方法,就是通过资源文件来引用,这个之后介绍。第三个参数代表菜单项显示顺序的编号,编号小的显示在前面。
to group menu items
@Override
Publicboolean // Add 4 menu items, divided into 2 groups
int group1 =1 int gourp2 =2 Menu.add (group1, 1, 1, "Item 1" Menu.add (group1, 2, 2, "Item 2" Menu.add (gourp2, 3, 3, "Item 3" Menu.add (gourp2, 4, 4, "Item 4" // Display Menu
returntrue ;
}
You can group the menu items as above, and after grouping, you can use the methods provided in menu to manipulate the groups, as follows:
Menu.removegroup (group1); Delete a set of menus
Menu.setgroupvisible (gourp2, visible); Sets whether a set of menus is visible
Menu.setgroupenabled (GOURP2, enabled); Sets whether a set of menus can point
Menu.setgroupcheckable (Gourp2, checkable, exclusive); Set a check for a set of menus
Response menu Item
Android offers a variety of ways to respond to menu items, as described below
1, through the Onoptionsitemselected method
The most commonly used method is to override the activity class's callback method, which is onOptionsItemSelected(MenuItem)
called by Android whenever a menu item is clicked, and the clicked menu item is passed in.
@Override
Publicbooleanonoptionsitemselected (MenuItem item) {
Switch(Item.getitemid ()) {
Respond to each menu item (by the ID of the menu item)
case1:
Do something here
Break;
Case2:
Do something here
Break;
CASE3:
Do something here
Break;
Case4:
Do something here
Break;
Default:
To the parent class to handle events that are not handled
Returnsuper. onoptionsitemselected (item);
}
Returns true to indicate that the event of the menu item has been processed, and that the event does not need to be propagated anymore.
returntrue;
}
The above code can be used as a template to use the Onoptionsitemselected Method response menu , where the menu ID is hardcoded in the program for convenience, and you can use constants or resource IDs to make your code more robust.
2. Using Listeners
Although the first method is recommended, Android also provides a way to respond to menus like the Java Swing listener. There are two steps to using the listener:
First step: Create a Listener class
class Mymenuitemclicklistener implements Onmenuitemclicklistener {
@Override
Publicboolean Onmenuitemclick (MenuItem item) {
Do something here ...
Returntrue; Finish handling
}
}
Step Two: Register the Listener for the menu item
Menuitem.setonmenuitemclicklistener (New Mymenuitemclicklistener ());
The description of the Android document to the Onmenuitemclick (MenuItem Item) callback method is "Called when a menu item has been invoked. The first code is executed; If it returns true, no other callbacks would be executed. "It is visible that this method is performed before the onoptionsitemselected .
3. Using the intent Response menu
The 3rd way is to raise the Setintent (Intent Intent) method directly in MenuItem, so that Android will automatically be invoked when the menu is clicked startActivity(Intent)
. But personally startActivity(Intent)
, it's not as straightforward as calling it manually in Onoptionsitemselected's case.
Android Menu Details (iii)--submenu and Iconmenu
In our previous article on how to create and respond to the Options menu in Android, today we will explore submenus and icon menus.
Submenu Sub Menu
Submenus provide a natural way to organize menu items, which are used extensively in Windows and other OS GUI designs. Android also supports submenus, and you can easily create and respond to submenus with addsubmenu (int groupId, int itemId, int order, int titleres) methods.
@Override
PublicbooleanOncreateoptionsmenu (Menu menu) {
int base =Menu.first;
One menu can include multiple submenus
submenu submenu = Menu.addsubmenu (base, base+1, Menu.none, "System settings");
Submenus can include multiple menu items
MenuItem menuitem1 = Submenu.add (base, base+1, Base+1, "Display Settings");
Submenu.add (base, base+2, base+2, "Network Settings");
Submenu.add (base, Base+3, Base+3, advanced settings);
Submenu.add (base, Base+4, Base+4, "Security Settings");
The submenu item does not support the display icon, so it makes no sense, though no error!
Menuitem1.seticon (r.drawable.displaysettings);
But the submenu itself is a support icon
Submenu.seticon (r.drawable.settings);
Show Menu Please return True
returntrue;
}
The above code shows how to create a submenu, the response of its menu item is actually the response of the ordinary menu item, the previous article has been introduced in detail, here no longer repeat. You can add an icon to a submenu in Android, but you don't see the icon for its menu items , which you need to be aware of. In addition to the SetIcon (int iconres) method in the code, there is also a setheadericon (int iconres) method to add the caption icon for the submenu item column, as shown in the third picture above.
Finally, it should be emphasized that the menu can contain multiple Submenu,submenu can contain multiple MenuItem (the relationship between these three see the Android menu in detail (a)-Understanding the menu in Android), But submenu cannot contain submenu, and submenus cannot be nested !!! The following code can be compiled, but will be faulted at run time.
Submenu.addsubmenu ("another submenu");
icons Menu icon Menus
Android supports displaying a variety of icons on the menu, which we used when creating submenus. Icon menu Strictly speaking is not a new type of menu, it is also very simple to use, the reason is a separate section is to illustrate the use of some of the limitations of icon. In Android, not so-called menu items can be labeled, the following menu items are not possible (this does not mean that the program will be error, but the run-time icon is not displayed):
- The expanded menu item. If you don't understand what an extended menu is, you can refer to the Android menu (a)--understand the menu in Android
- Menu items for submenus
- menu items for context menus
In addition, the menu item with icon cannot be added with a check mark. In short, although beautiful icons can add a lot to our application, but the misuse of icons is also counterproductive, the Android SDK to the Icon menu added these restrictions are also effective to prevent us from abusing the icon bar.
Conclusion
This article introduces the submenu in Android and the points to be aware of when adding icon to the menu item, the next article, "Android menu details (four)--Using context menu ContextMenu" will introduce the context menu of the use of contextual menus.
The Options menu, submenu and Icon menu are explained in detail in the "Android menu (ii)-Create and respond to Options menu" and "Android Menu details (iii)--submenu and Iconmenu". Today, we go on to another widely used menu-context menu.
ContextMenu Introduction
In Windows, we have been used to right-click on the file to perform "open", "name of Names", "Cut", "delete" and so on, the right button popup menu is the context menu. You might laugh: "Haha, you can't even use shortcut keys?" ”。 Cough, this ... Give me an example. Yes, the shortcuts in Windows can help us improve the efficiency of our operations, but this is not going to work in Android, Note: The context menu item for Android is not available with shortcut keys . Because the phone operates in a way that is different from the way the PC uses the mouse, Android pops up the context menu by long pressing a view element (PS: Most smartphones now have a full touchscreen, no physical keyboard, no need to use shortcut keys, The innovation is credited to Steve Jobs ' 07 mobile iphone, Old Joe retired, to pay tribute to him! )。 In addition, even icons and submenus are not available in the context menu item for Android. So, how does the context menu for Android work? See
, the context menu inherits the Android.view.Menu, so we can add menu items to the context menu as we do with the Options menu. The main difference between the context menu and the Options menu is that the owner of theOptions menu is activity, while the owner of the context menu is the view in the activity. Each activity has and has only one options Menu, which serves the entire activity. While an activity often has multiple view, not every view has a context menu, which requires us to display the Registerforcontextmenu (view view) to specify .
Although the owner of the context menu is View, the context menu is generated through the activity of the Oncreatecontextmenu (Contextmenumenu, view V, contextmenu.contextmenuinfo Menuinfo) method, which is much like the Oncreateoptionsmenu (Menu menu) method for generating Options menu. The difference is that Oncreateoptionsmenu is called only when the user presses the "menu" key for the first time , and Oncreatecontextmenu is called every time the user presses the view. And the view must already have the context menu registered.
Another notable is the contextmenuinfoin which the object of this class is passed into the Oncreatecontextmenu (Contextmenumenu, View V, Contextmenu.contextmenuinfo menuinfo) method, then what's the use of it? Sometimes, a view element needs to pass some information to the context menu, such as the ID of the view corresponding to the DB record, and this will use Contextmenuinfo. The view that needs to pass additional information needs to override the Getcontextmenuinfo () method to return a Contextmenuinfo implementation class object with data.
Introducing so much, here's a demo showing how to create and respond to context menus:
1. In the activity of the OnCreate (...) method to register the context menu for a view
2. In Oncreatecontextmenuinfo (...) In the build context menu.
3. In oncontextitemselected (...) The context menu item in response.
Demo: Using the context menu
1) Register context menu
Publicclass Samplecontextmenuactivity extendslistactivity {
privatestaticfinal String TAG = "Samplecontextmenuactivity";
@Override
ProtectedvoidonCreate (Bundle savedinstancestate) {
Super. OnCreate (savedinstancestate);
Display list
simpleshowlist ();
Registering a context menu for all list items
This. Registerforcontextmenu (Getlistview ());
}
PrivatevoidSimpleshowlist () {
List item
string[] Files =newString[] {
"File 1",
"File 2",
"File 3",
"File 4"
};
//Simple Array Adapter
Arrayadapter<</span>string> Adapter =new arrayadapter<</span>string>(
this,
Android. R.layout.simple_list_item_1,
files);
Set Adapter
This . Setlistadapter (adapter);
LOG.V (TAG, "Show Simple List");
}
}
2) Generate context menu
Override the method in the activity.
@Override
publicvoid // set context menu title
menu.setheadertitle ("file operation" menu.add (0, 1, menu.none, "sends" Menu.add (0, 2, menu.none, "marked as important" Menu.add (0, 3, menu.none, "Rename" Menu.add (0, 4, Menu.none , "Delete" );
}
3) Response context menu item
Similar to the Response Options menu, the only difference is that additional information can be obtained through menu info.
@Override
Publicbooleanoncontextitemselected (MenuItem item) {
Get the item information that is currently selected
Adaptercontextmenuinfo menuinfo =(Adaptercontextmenuinfo) item.getmenuinfo ();
LOG.V (TAG, "Context item seleted id=" +menuinfo.id);
Switch(Item.getitemid ()) {
Case1:
Do something
Break;
Case2:
Do something
Break;
CASE3:
Do something
Break;
Case4:
Do something
Break;
Default:
Returnsuper. oncontextitemselected (item);
}
Returntrue;
}
Run the program, call out the context menu several times, notice the output of Logcat, Oncreatecontextmenu is called every time.
Conclusion
So far, we've covered a variety of popular menus in Android, but by now we've been hard-coded to add menu items, and Android provides a much more convenient way to do so, as described in the next section, "Using the XML Build menu."
Android Menu Details (v)--Using the XML Build menu
Looking back at the previous few, we are directly in the code to add menu items, to the menu item grouping, etc., this is more traditional practice, it has some shortcomings. For example, in response to each menu item, we need to use constants to save the ID of each menu item, and so on. For this reason, Android provides a better way to define menu as the resource of the application, and the local support of the resources through Android, which makes it easier for us to create and respond to menus. This article describes how to use XML files to load and respond to menus, and we need to do these steps:
- Create a menu folder under the/res directory
- Using the menu-related element definition XML file in the menu directory, the file name is arbitrary, and Android automatically generates a resource ID for it. For example:r.menu.mainmenu the mainmenu.xml resource file corresponding to the menu directory
- Use the resource ID of the XML file to add the menu items that are defined in the XML file into the menu object
- When you respond to a menu item, use the resource ID corresponding to each item
Here's how to use XML to complete the Options menu in the Android menu (ii)-Create and respond to the option menus.
define a menu resource file
Create a menu folder under the Res directory and create an XML resource file under menu, which I call mainmenu.xml.
Android Menu Explanation--Understanding menu in Android