Easy Tutorial
❮ Zookeeper Acl Android Tutorial Activity Intro ❯

2.6.2 Menu

Category Android Basic Tutorial

Introduction to This Section:

>

This chapter introduces the Menu in Android, and there are several types of menus in Android:


1.OptionMenu (Option Menu)


1) How to use OptionMenu?

>

Answer: It's very simple, just override two methods, in fact, these two methods will be automatically generated when we create a project~ They are:

In addition to the above two methods that we can override, we can also override these three methods:

There are two ways to load the menu, one is to write the menu XML file directly, and then call: getMenuInflater().inflate(R.menu.menu_main, menu); to load the menu Or add it dynamically through code, the parameter menu of onCreateOptionsMenu, call the add method to add menu, add(group number of the menu item, ID, sort number, title), in addition, if the sort number is sorted in the order of addition, you can fill in 0!


2) Usage Example:

Running effect picture :

Code Implementation :

MainActivity.java :

public class MainActivity extends AppCompatActivity {

    //1. Define identifiers for menu items of different colors:
    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, "Red");
        menu.add(1, GREEN, 2, "Green");
        menu.add(1, BLUE, 3, "Blue");
        menu.add(1, YELLOW, 1, "Yellow");
        menu.add(1, GRAY, 5, "Gray");
        menu.add(1, CYAN, 6, "Cyan");
        menu.add(1, BLACK, 7, "Black");
        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, demonstrating the dynamic addition of menu items in OptionMenu (Option Menu) in Android 5.0,

registerForContextMenu(tv_context);

//Override methods related to ContextMenu
@Override
//Override the creation method for the context menu
public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenu.ContextMenuInfo menuInfo) {
    MenuInflater inflator = new MenuInflater(this);
    inflator.inflate(R.menu.menu_context, menu);
    super.onCreateContextMenu(menu, v, menuInfo);
}

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

Well, it's that simple~ You can set contexts for multiple Views, switch(v.getId) you know~
Also, just like the submenus we will talk about later, context menus cannot display icons!

---

## 3.SubMenu(Submenus)

The so-called submenu is simply another <**menu**> nested within an <**item**>

### Code Example:

**Running Effect Picture**

**Implementation Code:**

Write the Menu file for 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:title="Submenu Demo~"> <menu> <group android:checkableBehavior = "none"> <item android:id="@+id/one" android:title = "Submenu One"/> <item android:id="@+id/two" android:title = "Submenu Two"/> <item android:id="@+id/three" android:title = "Submenu Three"/> </group> </menu> </item> </menu>


Then we change the content of the above two context menu methods and replace it with the following code:


public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { //Submenu part: MenuInflater inflator = new MenuInflater(this); inflator.inflate(R.menu.menu_sub, menu); super.onCreateContextMenu(menu, v, menuInfo); }

public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.one: Toast.makeText(MainActivity.this,"You clicked Submenu One",Toast.LENGTH_SHORT).show(); break; case R.id.two: item.setCheckable(true); Toast.makeText(MainActivity.this,"You clicked Submenu Two",Toast.LENGTH_SHORT).show(); break; case R.id.three: Toast.makeText(MainActivity.this,"You clicked Submenu Three",Toast.LENGTH_SHORT).show(); item.setCheckable(true); break; } return true; }


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

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

---

## 4.PopupMenu(Pop-up Menu)

A thing similar to PopupWindow, it can conveniently display a pop-up menu under a specified View, and
its menu options can come from Menu resources. Let's write a simple example to use this thing~

### Usage Example:

**Running Effect Picture:**

**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 in the layout, 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,"You clicked the Little Pig~", Toast.LENGTH_SHORT).show(); break; case R.id.bpig: Toast.makeText(MainActivity.this,"You clicked the Big Pig~", Toast.LENGTH_SHORT).show(); break; } return true; } }); popup.show(); }

❮ Zookeeper Acl Android Tutorial Activity Intro ❯