Android menu items and android menu items

Source: Internet
Author: User

Android menu items and android menu items
I. Introduction:

Menus are common user interface components in many applications.

Before Android, Android devices provide a special "menu" button to present some common user operations,

Later than Android, Android provides an operation bar to complete the "menu" function.

About the menu official introduction: Ii. Classification: 1. OptionsMenu (option menu)

              

Android 2.3.X or later versions: Android3.0 and later

 

Android 2.3.X or a later version. When you press the "menu" button (entity button), the option menu content will appear at the bottom of the screen;

Android3.0 and later versions, the items in the option menu will appear in the Operation bar. By default, the system places all items in the Action overflow menu. You can use the action overflow menu icon on the right of the action bar (or press the "menu" button of the device (if any) to display

Indicates the operation overflow menu. However, the menu options can be directly promoted to the operation bar for display in the tem android: showAsAction = "ifRoom.

*: Not all apps will have menus in the Operation bar, which depends on the app design. If the app requires its own operation bar, design it as needed, if it is the system's default operation bar, there will be a menu.

--- By rewriting onCreateOptionsMenu () to create an option Menu, you can extend the Menu resources (defined in XML) to the Menu provided in the callback:

Eg:

 

Public boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. main, menu); // add menu. add ("add option menu"); // The first-level menu that is directly added with the same effect. addSubMenu ("add option menu Sub-menu"); // query and modify attribute menu. findItem (R. id. action_settings ). setTitle ("set"); return true ;}

 

--- Processing click events: When you select a project from the Options menu (including the operation items in the Operation bar), the system calls the onOptionsItemSelected () method of Activity. This method will pass the selected MenuItem. You can call the getItemId () method

Identifies a project. This method returns the unique ID of a menu item. You can match this ID with a known menu item for proper operations.

Eg:

public boolean onOptionsItemSelected(MenuItem item) {    switch (item.getItemId()) {        case R.id.new_game:            newGame();            return true;        case R.id.help:            showHelp();            return true;        default:            return super.onOptionsItemSelected(item);    }}
2. ContextMenu)

The Context Menu provides many operations that affect a specific project or context framework in the UI. You can provide context menus for any view, but these menus are usually used for ListView, GridView, or you can directly operate on projects in other View sets of each project.

The Android system provides two methods for context operations:

(1) Use the floating context menu

When you hold down a view that supports context menus, the menu is displayed as a floating list of menu items (similar to a dialog box ). You can perform context operations on a project at a time. For example:

To create a floating context menu:

1. Call registerForContextMenu () to bind the menu to a specific view. If the view is listview or gridview, the menu is bound to all items.

2. Implement the onCreateContextMenu () method in the Activity.
When the registered view receives a long press event, the system calls your onCreateContextMenu () method. In this method, you can define menu items by expanding menu resources. For example:

3. Implement onContextItemSelected (). When you select a menu item, the system calls this method so that you can perform appropriate operations. For example:

Public boolean onContextItemSelected (MenuItem item) {switch (item. getItemId () {case R. id. context_menu_1: Toast. makeText (getApplicationContext (), "Select menu 1, what do you want to do, do it yourself... ", 0 ). show (); return true; default: return super. onContextItemSelected (item );}}
(2) Use the context Operation Mode

The context action bar is displayed at the top of the screen, including the operation items that affect the selected items. When this mode is active, you can perform multiple operations at the same time (if the application permits ). For example:

To create a context menu, follow these steps:

A: Enable the context operation mode for A single view

1: implement the ActionMode. Callback interface. In the callback method, you can specify operations for the context operation column and respond to click events of the operation project.

2: Call startActionMode () when you need to display the operation bar (for example, you can press the view (). For example:

 

Private ActionMode. Callback mActionModeCallback = new ActionMode. Callback () {/*** called after onCreateActionMode (). If false is returned, nothing is done. * // @ Override public boolean onPrepareActionMode (ActionMode mode, Menu menu) {return false;} @ Override public void onDestroyActionMode (ActionMode mode) {// convenient memory reclaim actionMode = null ;} /*** when the actionmode is created and the startActionMode () method is called, call back this method * Here you can bind the menu to the context operation mode */@ Override public boolean onCreateActionMode (ActionMode mode, menu menu) {MenuInflater menuInflater = mode. getMenuInflater (); menuInflater. inflate (R. menu. context_menu, menu); return true;}/*** callback when the context menu bound to the actionMode is clicked */@ Override public boolean onActionItemClicked (ActionMode mode, MenuItem item) {switch (item. getItemId () {case R. id. context_menu_1: // Select menu 1, and I will change the text of button2 .. button2.setText (item. getTitle (); // After the menu task is completed, it is best to destroy the actionMode object. do not occupy the memory actionMode for a long time. finish (); return true; default: return false ;}}};

B: There is a group of items in ListView or GridView (or other extensions of AbsListView), and users must be allowed to perform batch processing.

Steps:
1: Use setMultiChoiceModeListener () to set the implementation Class Object of the AbsListView. MultiChoiceModeListener interface.
2: Use setChoiceMode () to set the selection mode to CHOICE_MODE_MULTIPLE_MODAL;

listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

Eg:

Lv = (ListView) findViewById (R. id. lv); strings = new ArrayList <String> (); strings. add ("item1"); strings. add ("item2"); strings. add ("item3"); adapter = new ArrayAdapter <String> (this, android. r. layout. simple_list_item_1, strings); lv. setAdapter (adapter); // sets the context operation mode lv. setChoiceMode (ListView. CHOICE_MODE_MULTIPLE_MODAL); lv. setMultiChoiceModeListener (new MultiChoiceModeListener () {@ Override public boolean onPrepareActionMode (ActionMode, Menu menu) {return false;} @ Override public void onDestroyActionMode (ActionMode) mode) {}@ Override public boolean onCreateActionMode (ActionMode mode, Menu menu) {MenuInflater menuInflater = mode. getMenuInflater (); menuInflater. inflate (R. menu. context_menu, menu); return true;} @ Override public boolean onActionItemClicked (ActionMode mode, MenuItem item) {Log. v ("zoubo", "onActionItemClicked .. "); switch (item. getItemId () {case R. id. context_menu_1: // Select menu 1 and add an item strings. add ("item4"); adapter. notifyDataSetChanged (); // local mode. You do not need to maintain its lifecycle. // mode. finish (); return true; default: return false;}/*** call */@ Override public void onItemCheckedStateChanged (ActionMode mode, int position, long id, boolean checked) {Log. v ("zoubo", "onItemCheckedStateChanged .. ");}});

*: Now, When you select a project by means of a long press, the system will call the onCreateActionMode () method and display the context operation column containing the specified operation.

In some cases, if context operations provide frequently-used operation items, you may need to add a check box or similar UI element to allow users to select a project, because they may not find long-pressed behaviors.

When you select this check box, you can use setItemChecked () to set the corresponding list items to the selected status to call the context operation mode.

2. PopupMenu (pop-up menu)

The modal menu of the View. If the space is sufficient, it is displayed below the positioning view; otherwise, it is displayed above it.

It is generally used in the following scenarios:

Operations related to specific content provide an overflow style menu (for example, Gmail email header)

Provide another part of the command statement (for example, mark as "add" and use different "add" options to generate the pop-up menu button)

Provides a drop-down menu similar to a Spinner and does not retain permanent options.

Eg:

ImageView iv1 = (ImageView) findViewById(R.id.iv1);     iv1.setOnClickListener(new OnClickListener() {              @Override       public void onClick(View v) {          PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);          MenuInflater menuInflater = popupMenu.getMenuInflater();          menuInflater.inflate(R.menu.popup_menu, popupMenu.getMenu());          popupMenu.show();          popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {                        @Override            public boolean onMenuItemClick(MenuItem item) {               switch (item.getItemId()) {               case R.id.popup_menu_1:                 return true;               default:                 return false;               }            }          });       }     });

PopupWindow:

PopupWidow provides a native Control for implementing custom menus. It can specify the view object that you have drawn as an anchor for the pop-up menu to determine the surrounding area of the view and control its specific appearance location.

Eg:

Button btn3 = (Button) findViewById (R. id. btn3); btn3.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub View contentView = LayoutInflater. from (v. getContext ()). inflate (R. layout. popup_menu, null); PopupWindow popupWindow = new PopupWindow (contentView, LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); // the lower part of the view appears // popupWindow. showAsDropDown (v); // if the background of PopupWindow is not set, the pop-up window cannot be dismiss when you click the external region or Back key. setBackgroundDrawable (getResources (). getDrawable (R. drawable. q2); popupWindow. setOutsideTouchable (true); popupWindow. showAtLocation (v, Gravity. TOP, (int) v. getX (), (int) v. getY ());}});

*: In the Code, if you need to click the external button to make the popupwindow disappear, you must call these two codes:
PopupWindow. setBackgroundDrawable (getResources (). getDrawable (R. drawable. q2 ));
PopupWindow. setOutsideTouchable (true );

Implementation of the effect of the popupWindow mask:
Layout:

<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: id = "@ + id/ll" android: layout_width = "match_parent" android: layout_height = "match_parent" android: background = "# b0000000" android: orientation = "vertical"> final PopupWindow popupWindow = new PopupWindow (inflate, RelativeLayout. layoutParams. MATCH_PARENT, RelativeLayout. layoutParams. WRAP_CONTENT); // click an area outside the user's visible range to make the window disappear. setOnTouchListener (new View. onTouchListener () {public boolean onTouch (View v, MotionEvent event) {int height = inflate. findViewById (TV ). getTop (); int y = (int) event. getY (); if (event. getAction () = MotionEvent. ACTION_UP) {if (y 

  

 

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.