Use of Menu of UI control (1), uimenu

Source: Internet
Author: User

Use of Menu of UI control (1), uimenu
[Android Development]: Use of Menu of UI control (1) in June April 15, 2013, the overall attention was 6876 characters. The font size was small, and the comment was closed. In the beginning, let's talk about how to use menus in Android. Menus are common components in applications, it mainly provides a friendly and focused user experience. You can use Menu APIs in your Activity to provide operations for user actions and other options. From Android 3.0, Android devices no longer provide a dedicated menu button, but rely on a menu panel with six independent options, and provide an Action Bar to display user behavior. Therefore, in the higher version, the menu application will be relatively small. 1. Three menu display Methods

1). Options menu and action bar2). Context menu and contextual action mode3). Popup menu
2. Today we will introduce the first way to use Menu: Options menu and action bar [action bar, which will be explained in detail later.] 1)
Options menu

Options menu is a main component of menu Options in an Activity. It is used in global apps, such as Search, Compose email, and Settings ."

In Android 2.3 or earlier versions, you can click the menu button to bring up the menu option Panel. In Android 3.0 advanced version, this option menu has been replaced by the Action Bar component that directly operates options on the screen or pops up options. From Android 3.0, the menu button is not in favor of use (many devices do not have the menu button), so you should move to the ActionBar to provide users with other options to operate the action. For details, see Creating an Options Menu.

2)
Options menu Creation
Options menu has two usage methods: one is to create a Menu directly in the code, and the other is to use the add () method to view the add () method in the menu API document.

Public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title)
GroudId: Group ID, which is used to process and sort menu items in batches.
ItemId: the subitem ID, which is the unique identifier of each menu item.
Order: Specify the order of menu items in the option menu
Titler: menu title

 

The other is to define a menu in XML. The reference code is as follows:
@Overridepublic boolean onCreateOptionsMenu(Menu menu) {    MenuInflater inflater = getMenuInflater();    inflater.inflate(R.menu.game_menu, menu);    return true;}
3) trigger event

Trigger the click event. When you select an item from the menu option (including action items in the ActionBar), the system will call the onOptionsItemSelected () method of your Activity, this method will be selected based on MenuItems. You can call getItemId () to determine the option ID. This ID value is the id attribute value defined in the menu resource or you can use add () an integer value given by the method.

View Menu in API documentation
By default, every Activity supports an options menu of actions or options. you can add items to this menu and handle clicks on your additions. the easiest way of adding menu items is inflating an XML file into the Menu via MenuInflater.
The easiest way of attaching code to clicks is via onOptionsItemSelected (MenuItem) and onContextItemSelected (MenuItem ).

 

4) Create an Option menu in the code.

1) Layout file activity_main.xml

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" ></RelativeLayout>

2) Main Code MainActivity. java

 

Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);} // you can use either of the following methods to create a menu: Use inflate to load XML, for example, add () method. @ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater (). inflate (R. menu. main, menu); the first method of use // set menu options. Generally, it is best to set MenuItem menuItem = menu. add (1001,100, 1, "menu 1"); // menuItem. setIcon (R. drawable. ic_launcher); // the icon is not recommended for later versions. The added icon is not displayed. MenuItem menuItem2 = menu. add (1001,101, 2, "menu 2"); MenuItem menuItem3 = menu. add (1001,102, 3, "menu 3"); menuItem3.setShortcut ('C', 'C'); // set the menu shortcut key to return true ;} // click the event @ Override public boolean onOptionsItemSelected (MenuItem item) {switch (item. getItemId () {case 100: Toast. makeText (MainActivity. this, "click menu 1 option", 3 ). show (); break; case 101: // menu options are usually the operations that the user jumps to other activities, use the // setIntent () method, Of course, some information can also be transmitted through Intent. Intent intent = new Intent (MainActivity. this, NextActivity. class); item. setIntent (intent); break; case 102: break; default: break;} return super. onOptionsItemSelected (item );}}

3) Layout file next_activity.xml of another Activity to be jumped

 

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ProgressBar        android:id="@+id/progressBar1"       >package com.android.menudemo;import android.app.Activity;import android.os.Bundle;public class NextActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        setContentView(R.layout.next_activity);    }}

4) program execution results

5.
Define an Option Menu in XML
Next, let's take a look at the second way to define menus, and use XML to define menus. For all menu types, android provides a standard XML format to define menu options instead of writing menus in Activity. You can define a menu and all its options in XML menu resources, you can use inflate Menu resources (load it as a Menu object) in your activity or fragment.

 

1) There are several advantages to using this method: 1. define the structure of menus easily displayed in xml. 2. you can separate the menu content from the application code. in different platform versions, screen sizes, and other configurations, you can use the application resource framework to create flexible menu configurations.
2) define the menu position:
Define menu options, create an xml file in your project directory: res/menu/, and create the following tag elements of the menu.
<Menu>
Define a Menu, which is the content owner of the menu options. The <Menu> label element must be the root node of the file, it also supports one or more <item> and <group> elements.
<Item>
Create a MenuItem, which is a single option in the menu. This element can contain a nested <menu> element to create a sub menu. 

 

<Item> attributes of an element include:
Android: id
Android: icon
Android: title
Android: showAsAction


Android: showAsAction [this attribute is important: it is an activity option in the aciton bar and can be used to specify when or how to display]
= "Never" indicates that it will not be displayed in the ActionBar title bar. view the android: showAsAction of the API document: Menu Resource.
For various attributes, see the following two. Other readers can refer to them.

 

IfRoom: You can place this option in the navigation bar if it has space. WithText: You can set the title in the navigation bar. The title is defined by android: title.
Android: orderInCategory indicates the order of placement. It is not necessarily calculated from 0, but must be greater than or equal to 0. It is recommended from 0, 1, 2, 3 .... in this way, it is given in sequence and consistent with the XML format.

 


<Group>
This is an optional label that allows you to classify menu options so that they can share some configurations, such as activity status and display hidden status. View more information
Creating Menu Groups.

6. Main Code Implementation

1) The menu file menu. xml is in the directory
Res/menu.

 

<Menu xmlns: android = "http://schemas.android.com/apk/res/android"> <item android: id = "@ + id/action_settings" android: icon = "@ drawable/two" android: orderInCategory = "100" android: showAsAction = "ifRoom | withText" android: title = "@ string/action_settings"> <menu> <item android: id = "@ + id/create_new" android: title = "new file"/> <item android: id = "@ + id/open" android: title = "Open File"/> </menu> </item> <item android: id = "@ + id/sys" android: icon = "@ drawable/two" android: orderInCategory = "101" android: showAsAction = "never" android: title = "User menu"> <menu> <group android: id = "@ + id/group1"> <item android: id = "@ + id/load" android: title = "loading Files"> </item> </group> <group android: id = "@ + id/group1"> <item android: id = "@ + id/save" android: title = "save file"> </item> </group> </menu> </item> </menu>

2) Main Code MainActivity. java

 

Package com. android. menudemo; import android. OS. bundle; import android. app. activity; import android. content. intent; import android. view. menu; import android. view. menuItem; import android. widget. toast; public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true;} @ Override public boolean onMenuItemSelected (int featureId, MenuItem item) {switch (item. getItemId () {case R. id. create_new: Intent intent = new Intent (MainActivity. this, NextActivity. class); item. setIntent (intent); break; case R. id. open: Toast. makeText (MainActivity. this, "Open File", 3 ). show (); break; case R. id. load: Toast. makeText (MainActivity. this, "loading Files", 3 ). show (); break; case R. id. save: Toast. makeText (MainActivity. this, "save files", 3 ). show (); break; default: break;} return super. onMenuItemSelected (featureId, item );}}

7. program execution results


Http://developer.android.com/guide/topics/ui/menus.html

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.