In this lesson we will:

 - create menu items

 

Translated by Taras Leskiv (http://android-by-example.blogspot.com/)

I guess there is no point in explaining what a menu is. It is displayed when Menu button is clicked. Let’s create our own menu.

 

Create a project:

Project name: P0131_MenuSimple
Build Target: Android 2.3.3
Application name: MenuSimple
Package name: ru.startandroid.develop.menusimple
Create Activity: MainActivity

 

Open MainActivity.java. onCreateOptionsMenu method is responsible for creating a menu. Menu object is passed to this method as a parameter. We will add our menu items into this object. The adding procedure is simple, add method is used. This method takes the text of the menu item as a parameter. Let’s add 4 items

    public boolean onCreateOptionsMenu(Menu menu) {
      // TODO Auto-generated method stub
      
      menu.add("menu1");
      menu.add("menu2");
      menu.add("menu3");
      menu.add("menu4");
      
      return super.onCreateOptionsMenu(menu);
    }

onCreateOptionsMenu method returns a boolean result. True - show menu, False - do not show. So we could have made a checking of some condition, and as a result of this check do not show a menu returning False. We don’t need this for now, so we delegate this choice to the method of superclass, it returns True by default.

Save everything, run the application and click the emulator menu button.

Four menu items appeared. Clicking them will do nothing as listener is not implemented.

Activity is a listener and method is called onOptionsItemSelected. It receives menu item which has been clicked as a parameter - MenuItem. It is possible to define which menu item has been clicked by getTitle method. Let’s show a Toast message with the text of the menu item clicked. Method must return a boolean value at the end. And we delegate it to the superclass again:

    public boolean onOptionsItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
      Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
      return super.onOptionsItemSelected(item);
    }

 

Complete code:

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
      // TODO Auto-generated method stub
      
      menu.add("menu1");
      menu.add("menu2");
      menu.add("menu3");
      menu.add("menu4");
      
      return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
      Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
      return super.onOptionsItemSelected(item);
    }
    
}

 

It is not the best practice to define the clicked menu item by its title. Later we will do this by ID. But to do so, we have to create menu slightly differently.

 

In the next lesson we will:

- create menu items with IDs
- group and sort menu items


Присоединяйтесь к нам в Telegram:

- в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

- в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance 

- ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня




Language