Lesson 14. Menu, groups, order. MenuInflater and xml menu.

Lesson 14. Menu, groups, order. MenuInflater and xml menu.

In this lesson we:

– create menu items c ID
– group and sort menu items

In the last lesson, we looked at the easiest way to create menus using the add (CharSequence title) method, we only provided text for input. Consider another implementation of this method – add (int groupId, int itemId, int order, CharSequence title). In this method 4 parameters to the entrance:

groupId is the group ID of which the menu item is a part
itemId – Menu item ID
order – to specify the order in which the menu items are displayed
title – the text that will be displayed

To show how all these parameters are used, let’s create an application. It will be on the screen TextView and CheckBox:
– TextView will display which menu item was selected
– CheckBox will determine whether to display a normal menu or an expanded menu. This will be done through menu groups.

Immediately clarify, the concept of “ordinary” and “advanced” are not Android concepts, but just my name. That is, when the application is started and the user presses the menu button, he sees the “normal” menu. If it turns on CheckBox, it will display an “expanded” menu with more items.

Create a project:

Project name: P0141_MenuAdv
Build Target: Android 2.3.3
Application name: MenuAdv
Package name: ru.startandroid.develop.menuadv
Create Activity: MainActivity

open main.xml, lady ID existing TextView, We will erase its text and create it CheckBox. code:


open MainActivity.java and class MainActivity fill in the following code:

public class MainActivity extends Activity {
  // Элементы экрана
  TextView tv;
  CheckBox chb;
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        // находим элементы
        tv = (TextView) findViewById(R.id.textView);
        chb = (CheckBox) findViewById(R.id.chbExtMenu);
    // создание меню
    public boolean onCreateOptionsMenu(Menu menu) {
      // TODO Auto-generated method stub
      // добавляем пункты меню
      menu.add(0, 1, 0, "add");
      menu.add(0, 2, 0, "edit");
      menu.add(0, 3, 3, "delete");
      menu.add(1, 4, 1, "copy");
      menu.add(1, 5, 2, "paste");
      menu.add(1, 6, 4, "exit");
      return super.onCreateOptionsMenu(menu);
    // обновление меню
    public boolean onPrepareOptionsMenu(Menu menu) {
      // TODO Auto-generated method stub
      // пункты меню с ID группы = 1 видны, если в CheckBox стоит галка
      menu.setGroupVisible(1, chb.isChecked());
      return super.onPrepareOptionsMenu(menu);

    // обработка нажатий
    public boolean onOptionsItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
      StringBuilder sb = new StringBuilder();

      // Выведем в TextView информацию о нажатом пункте меню 
      sb.append("Item Menu");
      sb.append("rn groupId: " + String.valueOf(item.getGroupId()));
      sb.append("rn itemId: " + String.valueOf(item.getItemId()));
      sb.append("rn order: " + String.valueOf(item.getOrder()));
      sb.append("rn title: " + item.getTitle());
      return super.onOptionsItemSelected(item);

Don’t forget update import (CTRL + SHIFT + O).

Let’s parse the writing. We use the following methods:

onCreateOptionsMenu – Called only at the first show menu. Creates a menu and is no longer used. Here we add items to the menu.

onPrepareOptionsMenu – Called each time before the menu is available. Here we make changes to the already created menu, if necessary

onOptionsItemSelected – Invoked when pressed menu items. Here we determine which menu item was clicked.

In the method onCreateOptionsMenu we add 6 menu items. Let’s pay attention to the parameters of the method Add.

The first parameter is Group ID. In the first three items it is zero, in the other three – 1. That is, menu items copy, paste and exit grouped with ID = 1. Visually, this does not show in any way – they are not different in color or anything else. We will use the group ID in the implementation onPrepareOptionsMenu.

The second parameter is Menu item ID. The handler is used to determine which menu item has been clicked. We will use it in onOptionsItemSelected.

The third parameter – defines item position menu. This parameter is used to determine the order of items when the menu is displayed. used sorting in ascending orderThat is from the smaller order to more.

The fourth parameter is textWhich will be displayed in the menu item. Everything is clear here.

In the method onPrepareOptionsMenu the object is transmitted Menu and we can work with him. In this example, we call setGroupVisible. This method allows hide display menu items. There are two parameters to the input – Group ID and boolean-value. As the group ID we write – 1 (The same group with ID = 1, which contains copy, paste, and exit items), and use the state as a boolean parameter CheckBox. If enabled, the menu items (with groups with ID = 1) Will be displayed if disabled – will not be displayed.

Let’s save everything and launch the application.



Depending on the condition CheckBox the menu is visible 3 or 6 points.

Take a look at order points. They are sorted by parameter order on growth. if order in several points coincides, Then these items are posted in the order they were created in the onCreateOptionsMenu method.

Clicking on any menu item triggers the method onOptionsItemSelected. In it we output in TextView information about the clicked item. You can verify this information so that we are coding when creating menu items. All parameters must match. The order, for convenience, I did the same as in the add method: groupId, itemId, order, title.

Try adding a few more menu items to get them done more than six. And see how they appear.

To simplify the code, I used directly digits for the group IDs and menu item IDs. And generally it is recommended to use constants, in the future I will use them.

XML menu

There is another, more convenient and better way to create a menu – using xml files, similar to layout files when creating a screen. To get the menus we created programmatically in this lesson, we need to create a file in the res / menu folder mymenu.xml:


If there is no menu folder in the res folder, create one. Right-click on res, select New> Android Resource Directory, in Resource type select menu and press OK.

item is a menu item, group – a group. In the attributes ID we use the same scheme as the ID of the screen components, that is, we write @ + id / and Eclipse will create these IDs in R.java itself. Attribute orderInCategory is the order of points, a title – text.

In the method onCreateOptionsMenu now we do not have to manually encode the creation of each item, we simply link the menu that is given to us and our xml file.

  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mymenu, menu);
    return super.onCreateOptionsMenu(menu);

Using the method getMenuInflater we get MenuInflater and call it inflate method. We send our file to the input mymenu.xml from the res / menu folder and object menu. MenuInflater takes a menu object and fills it with items according to the mymenu.xml file.

If you want to hide the group, follow the same setGroupVisible method and pass R.id.group1 as the group ID there.

You can see the attributes for the menu xml file here in detail.

I recommend that you try and test both ways of creating a menu. Software creation is more flexible, and xml reduces code.

In the next lesson:

– create a context menu

Discuss in the forum [191 replies]

Leave a Comment