Menu


Introduction to this section:

This chapter brings you the Menu (menu) in Android, and the menus in Android include the following types:

  • OptionMenu: Option menu, the most common menu in android, called through the Menu key
  • SubMenu: Submenu, clicking on the submenu in android will pop up a display The floating box of the submenu item, Submenus do not support nesting, that is, they cannot include other submenus
  • ContextMenu: Context menu, the menu that appears after long pressing a view component, the component needs to register the context menu In this section, let’s learn how to use these menus in Yiyi~ PS: Official document: menus

##1.OptionMenu(Option Menu)


1) How to use OptionMenu?

Answer: Very simple, just rewrite two methods. In fact, these two methods will be automatically generated when we create the project~ They are:

    public boolean
  • onCreateOptionsMenu(Menu menu): Call OptionMenu and complete the menu initialization here
  • public boolean
  • onOptionsItemSelected (MenuItem item): Triggered when the menu item is selected. Event processing is completed here
Of course, in addition to the above two methods, we can also override these three methods:

    public void
  • onOptionsMenuClosed(Menu menu): This method will be called when the menu is closed
  • public boolean
  • onPrepareOptionsMenu(Menu menu): Before the options menu is displayed This method will be called, The menu can be adjusted here (dynamically loaded menu list)
  • public boolean
  • onMenuOpened(int featureId, Menu menu): This method will be called after the option menu is opened
There are two ways to load the menu. One is to directly write the menu XML file and then call:

getMenuInflater().inflate(R.menu.menu_main, menu);Loading menu Or add it dynamically through code, parameter menu of onCreateOptionsMenu, call the add method to add Menu, add (group number, ID, sort number, title of the menu item), and if the sort number is sorted by the order of addition, just fill in 0!


2) Usage example:

Running renderings:

1.gif

Code implementation

MainActivity.java

public class MainActivity extends AppCompatActivity {

    //1.定义不同颜色的菜单项的标识:
    final private int RED = 110;
    final private int GREEN = 111;
    final private int BLUE = 112;
    final private int YELLOW = 113;
    final private int GRAY= 114;
    final private int CYAN= 115;
    final private int BLACK= 116;

    private TextView tv_test;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_test = (TextView) findViewById(R.id.tv_test);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        menu.add(1,RED,4,"红色");
        menu.add(1,GREEN,2,"绿色");
        menu.add(1,BLUE,3,"蓝色");
        menu.add(1,YELLOW,1,"黄色");
        menu.add(1,GRAY,5,"灰色");
        menu.add(1,CYAN,6,"蓝绿色");
        menu.add(1,BLACK,7,"黑色");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch (id){
            case RED:
                tv_test.setTextColor(Color.RED);
                break;
            case GREEN:
                tv_test.setTextColor(Color.GREEN);
                break;
            case BLUE:
                tv_test.setTextColor(Color.BLUE);
                break;
            case YELLOW:
                tv_test.setTextColor(Color.YELLOW);
                break;
            case GRAY:
                tv_test.setTextColor(Color.GRAY);
                break;
            case CYAN:
                tv_test.setTextColor(Color.CYAN);
                break;
            case BLACK:
                tv_test.setTextColor(Color.BLACK);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

Code Analysis:

The above code is very simple. It demonstrates to you how to dynamically add menus in OptionMenu (option menu) in Android 5.0. And event processing, determine which item the user clicked based on the ID, and then perform the corresponding operation! In addition, one thing to note is that the options menu has gone through three stages of transition: In Android 2.3.x or lower version, because most models at this stage have Menu keys, At this stage, click the Menu button to pop up the menu:

2.png

. In Android 3.0 or higher, it is the setting menu in the ActionBar introduced in 3.0:

3.png

In versions above 5.0, it is in the ToolBar. After clicking, an overflow menu style appears

4.png

In addition, through To define Menu in XML, let’s post a simple reference code:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns :android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ ic_new_game"
android:title="@string/new_game"
android:showAsAction="ifRoom"/>
<item android:id="@+id/help"
android: icon="@drawable/ic_help"
android:title="@string/help" />
</menu>

Others, please check the documentation yourself~


2.ContextMenu(context menu)

As we said at the beginning, it appears after long pressing a View Menu, we need to register the context menu for this View!


1) How to use ContextMenu?

Answer: The process used is as follows:

  • Step 1: Rewrite the onCreateContextMenu() method
  • Step 2: Register the context menu for the view component, use the registerForContextMenu() method, the parameter is View
  • Step 3: Override the onContextItemSelected() method to specify an event listener for the menu item

For the OptionMenu above, we used the Java code method to complete the addition of menu items. Here we use the XML file method to generate our CotnextMenu. In addition, regarding whether to use Java code to generate the menu or use XML to generate the menu, It is recommended to use the latter to define the menu, which can reduce the code bloat of the Java code and does not need to use code allocation every time id, you only need to modify the XML file to modify the content of the menu, which provides better decoupling to a certain extent. Low coupling, high cohesion, right~


2) Usage example:

Running renderings:

5.gif

Implementation code

Let’s first write the menu XML file of the options menu:

menu_context.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/ android">
<!-- Define a set of radio buttons -->
<!-- There are three optional values ​​for checkableBehavior: single is set to radio selection, all is multi-selection, none is a normal option -->
<group android:checkableBehavior="none">
<item android:id="@+id/blue" android:title="@string/font_blue" />
; <item android:id="@+id/green" android:title="@string/font_green"/>
; <item android:id="@+id/red" android:title="@string/font_red"/>
</group>
</menu>

Then we add a TextView based on the options menu, and then add the following things:

private TextView tv_context;
tv_context = (TextView) findViewById(R.id .tv_context);
registerForContextMenu(tv_context);

//Override methods related to ContextMenu
@Override
//Rewrite the context menu creation method
public void onCreateContextMenu( ContextMenu Menu, View v,
ContextMenu.ContextMenfo Menuinfo) {
Menuinflator Inflator = New Menuinflator (this);
Inflator.inflating XT, Menu);##.oncreateContextMenu ( menu, v, menuInfo);
}

//This method is triggered when the context menu is clicked
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item. getItemId()) {
            case R.id.blue:
        tv_context.setTextColor(Color.BLUE);          tv_context.setTextColor(Color .GREEN);
case R.id.red:
tv_context.setTextColor(Color.RED);
break;
}
          return true;
            

Okay, it’s that simple~ You can set context for multiple Views, you know switch(v.getId)~ In addition, like the submenu that will be discussed later, the context menu cannot display icons!


3.SubMenu(submenu)

The so-called submenu is just another layer of <**menu* nested in <**item**> *>That’s it

Code example:

Running renderings

6.gif

##Implementation code:

Write the Menu file of the submenu: menu_sub.xml:

##<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/submenu" android ; " android:title = "Submenu one"/>
                                                                                                                                                                 id="@+id/three" android:title = "Submenu three"/>
/menu>

Then we changed the contents of the two methods of the above context menu, and changed the code below:

# Public Void OncreateContextMenu (ContextMenu Menu, View V,
ContextMenuinfo Menuinfo) {
// Sub -menu part:
Menuinflaater Inflator = New Menuinflator (this);
Inflator.inflate (R.Menu.Menu_SUB, Menu); FO );
}

public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Toast.makeText(MainActivity .this,"You clicked on submenu one",Toast.LENGTH_SHORT).show();
                                                                                                                                       . Toast .makeText(MainActivity.this,"You clicked on submenu two",Toast.LENGTH_SHORT).show(); ,"You clicked on submenu three",Toast.LENGTH_SHORT).show();
         item.setCheckable(true);
           break;
                                                                                                                                
#

Okay, it's very simple, right? In addition, if you want to add a submenu in Java code, you can call addSubMenu()

For example: SubMenu file = menu.addSubMenu("File") ;file also needs addItem to add menu items!


4.PopupMenu (pop-up menu)

Something similar to PopupWindow, it can easily display a pop-up menu under the specified View, and His menu options can come from Menu resources. Let's write a simple example to use this stuff~

Usage example:

Running rendering:

7.gif

Implementation code:

Menu resource file: menu_pop.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/lpig" android:title="Little Pig" />
<item android:id="@+id/bpig" android:title=" Big Pig" />
</menu>

Add a button to the layout and then add a click event:

MainActivity.java:

btn_show_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(MainActivity.this,btn_show_menu);
                popup.getMenuInflater().inflate(R.menu.menu_pop, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.lpig:
                                Toast.makeText(MainActivity.this,"你点了小猪~",
                                Toast.LENGTH_SHORT).show();
                                break;
                            case R.id.bpig:
                                Toast.makeText(MainActivity.this,"你点了大猪~",
                                Toast.LENGTH_SHORT).show();
break;
                    
                                                                                                                                                                                                                       break; Popup.show();
}
});


It's very simple. Have you got the new skill?

5. Sample code download


MenuDemo1.zip

Summary of this section:


Okay, this section Introduced to you the three menus in Android, option menu, context menu and submenu. Finally It also explains a PopupMenu control. Only the basic usage is demonstrated here. You can refer to the documentation for other properties. Documentation is the best teacher~ Well, that’s all, thank you. By the way, it’s National Day today. I wish everyone a happy National Day!