the first month of training. Let's take a closer look at the menu. Both old Android 2.3 devices and new Android 4.0 phones will be considered.

Options Menu

The class is responsible for the menu android.view.Menu. Each activity is associated with one menu object. The menu itself contains menu items (class android.view.MenuItem) and submenu (class android.view.SubMenu).

When you press a button Menu on older phones, a set of menu items appears attached to the activity. The menu may contain icons. Such a menu can contain six items (as a rule). If there are more than six items, the extended menu is used - in this case, instead of the sixth item, the item appears Options(more). When this item is pressed, an extended menu is displayed with a list of items that did not fit in the main part of the option selection menu.

When the menu is opened for the first time, Android calls the method onCreateOptionsMenu(), passing an object as a parameter Menu. Menus can be created as resources in an XML file, or you can use the add().

In a standard project, when choosing a regular template, there is already a blank for a one-point menu Settings and a method call for the menu (you already know about this).

Creating a Menu Using Resources

Consider working with the menu through resources. To create a menu, resources are used that must be stored in an XML file. The file itself must be in the folder res/menu/ your project. The menu consists of the following items:

Specifies the menu that will contain the menu items. Element must be the root element in the XML structure of the file and may contain one or more elements and Creates menu items directly. This element can have a nested element to create a submenu Optionally, you can also use an invisible element container . This allows you to achieve some effects

Suppose we decide to use the menu for some game. Let's create new file game_menu.xml:

We have created a menu with two items. Each item includes the following attributes:

Android:id Identifier of the menu item by which the application can recognize when the user selects the menu item android:title The text that will be displayed in the menu

There are other attributes for the element item, for example android:icon="@drawable/home" will also display the icon for the menu item, and android:enabled="false" allows you to make the menu item unavailable.

Attribute android:titleCondensed used when the regular title is too wide to "fit" in the selected menu item.

Attribute android:orderInCategory defines the order in which MenuItems menu items are displayed.

When creating the menu, we pointed to string resources @string/new_game and @string/help. Need to add new lines in the file strings.xml:

New game Reference

Now we need to make changes in the activity class in which the menu will be displayed. The program should convert the menu resource we created into a program object. There is a special method for this purpose. MenuInflater.inflate(), which is called in a special method callback onCreateOptionsMenu(). This method is designed to display a menu when a button is pressed. MENU on device:

@Override public boolean onCreateOptionsMenu( menu menu) ( MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.game_menu, menu); return true; )

After pasting the code, the development environment will ask you to import the missing namespaces.

Import android.view.Menu; import android.view.MenuInflater;

Method onCreateOptionsMenu() the method initiates the first appearance of the menu on the screen and takes a Menu object as a parameter (for older devices). You can save a link to the menu and use it anywhere in your code as long as the method onCreateOptionsMenu() will not be called again. You should always use the parent class implementation of this handler, because it automatically includes additional system items in the menu if necessary. In new devices, the method is called when the activity is created. The method must return a value true to make the menu visible on the screen.

After starting the program, press the button MENU on the emulator to see the created menu.

Method getMenuInflater() returns an instance of the class menuinflater, which we use to read menu data from XML.

As you can see, the menu appears at the bottom of the screen. A total of six menu items can be displayed at the same time. If there are more points, then five points plus the sixth point will be displayed More, which will allow you to see the rest of the items. Let's test and add new menu items.

Let's add six points first.

Let's add one more item to the menu so that there are seven of them.

Selecting menu items

We have learned how to create a menu. But so far it is useless, since the menu items do not react in any way to our clicks. The method is used to handle clicks on menu items. onOptionsItemSelected(). The method recognizes the item selected by the user through MenuItem. We can now determine the selected item by calling getItemId(), which returns the ID of the menu item. Further through the operator switch it remains for us to define the necessary commands:

@Override public boolean onOptionsItemSelected(MenuItem item) ( // Operations for the selected menu item switch (item.getItemId()) ( case R.id.new_game: newGame(); return true; case R.id.help: showHelp() ; return true; default: return super.onOptionsItemSelected(item); ) ) public void newGame() ( edtext.setText("New game selected"); ) public void showHelp() ( edtext.setText("Help selected" ); )

Launch the application, call up the menu and select the first or second menu item. A message should appear in the text box.

In the given example getItemId() asks for an ID for the selected menu item and starts comparing via the switch selection statement with the IDs we set in the XML resources. When the required identifier is found, the handler for the given menu item is executed. If the program finds nothing, then the statement is executed default, which returns the super class.

In Android 3.0, you can add the attribute android:onclick in menu resources and you no longer need to use onOptionsItemSelected(). With help android:onclick you can specify the desired method when selecting a menu item.

// menu item attribute set to android:onClick="onMenuClick" public void onMenuClick(MenuItem item)( edtext.setText("Feed the cat selected"); )

Menu creation programmatically

Consider software creation menu for completeness. We will need to define a few constants for the menu items:

// identifiers for menu items private static final int IDM_OPEN = 101; private static final int IDM_SAVE = 102; public boolean onCreateOptionsMenu(Menu menu) ( // add menu items menu.add(Menu.NONE, IDM_OPEN, Menu.NONE, "Open"); menu.add(Menu.NONE, IDM_SAVE, Menu.NONE, "Save") ; )

At the method add() there are four options:

  • group identifier - allows you to associate a menu item with a group of other items on this menu
  • item identifier for menu item selection event handler
  • order of the item in the menu - allows you to determine the position in the menu. By default (Menu.NONE or 0) items go in the order specified in the code
  • title - the text that is displayed in the menu item. You can use a string resource

The method returns an object MenuItem, which can be used to set additional properties, such as set icon, hotkey, etc.

If you want to create a menu with icons, then use the method setIcon()

Menu.add(Menu.NONE, IDM_OPEN, Menu.NONE, "Open") .setIcon(R.drawable.icon_menu_open);

Recall again that icons can only be added to six menu items (or five, if there are more than six items).

Method onCreateOptionsMenu called by the system only once when the menu is created. If you need to update the menu while the program is running, use the callback method onPrepareOptionsMenu().

When a menu item is selected, the method is called onOptionsItemSelected, which passes the object MenuItem- menu item selected by the user. Using the method getItemId you can get the ID of the selected menu item. After identifying the menu item, you can write code to handle the menu selection event:

Public boolean onOptionsItemSelected(MenuItem item) ( switch (item.getItemId()) case IDM_OPEN: return true; case IDM_SAVE: return true; return false; )

Hotkeys

You can also set hotkeys for quick access using keyboard characters using several methods:

  • setAlphabeticShortcut(char) - adds a character
  • setNumericShortcut(int) - adds a number
  • setShortcut(char, int) - Adds a combination of character and number

For example, if you set the hotkey setAlphabeticShortcut("q");, then when you open the menu (or while holding down the MENU key), pressing the key Q selects this menu item. This hot key(or keyboard shortcut) will be shown as a tooltip displaying below the menu item name. Newer keyboards have a separate key ctrl, which works the same way as on regular keyboards.

Hotkeys can also be created via XML: android:alphabeticShortcut="c".

You can handle clicks through the activity method onKeyShortcut():

@Override public boolean onKeyShortcut(int keyCode, KeyEvent event) ( switch (keyCode) ( case KeyEvent.KEYCODE_R: Toast.makeText(this, "Reply", Toast.LENGTH_SHORT).show(); return true; default: return super. onKeyShortcut(keyCode, event); ) )

Creating a submenu

A submenu can be added to any menu except another submenu. The submenu is created in the callback method onCreateOptionsMenu() using the method addSubMenu() which returns an object submenu. To object submenu you can add additional items to this menu using the method add(). For example:

Public static final int IDM_HELP = 101; public static final int IDM_NEW = 201; public static final int IDM_OPEN = 202; public static final int IDM_SAVE = 203; public static final int IDM_CUT = 301; public static final int IDM_COPY = 302; public static final int IDM_PASTE = 303; @Override public boolean onCreateOptionsMenu(Menu menu) ( SubMenu subMenuFile = menu.addSubMenu("File"); subMenuFile.add(Menu.NONE, IDM_NEW, Menu.NONE, "New"); subMenuFile.add(Menu.NONE, IDM_OPEN , Menu.NONE, "Open"); subMenuFile.add(Menu.NONE, IDM_SAVE, Menu.NONE, "Save"); SubMenu subMenuEdit = menu.addSubMenu("Edit"); subMenuEdit.add(Menu.NONE, IDM_CUT , Menu.NONE, "Cut"); subMenuEdit.add(Menu.NONE, IDM_COPY, Menu.NONE, "Copy"); subMenuEdit.add(Menu.NONE, IDM_PASTE, Menu.NONE, "Paste"); menu. add(Menu.NONE, IDM_HELP, Menu.NONE, "Help"); return super.onCreateOptionsMenu(menu); ) @Override public boolean onOptionsItemSelected(MenuItem item) ( CharSequence message; switch (item.getItemId()) ( case IDM_NEW : message = "New item selected"; break; case IDM_OPEN: message = "Open item selected"; break; case IDM_SAVE: message = "Save item selected"; break; case IDM_CUT: message = "Cut item selected"; break; case IDM_COPY:message= "Copy item selected"; break; case IDM_PASTE: message = "Paste selected"; break; case IDM_HELP: message = "Help item selected"; break; default: return false; ) // display a notification about the selected menu item Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); return true; )

Now, when you select a menu item, another window with a submenu will appear. Try it yourself.

Adding checkboxes and radio buttons

You can add checkboxes or radio buttons to menu items. To add a checkbox or radio button for an individual menu item, you must use the method setCheckable():

MenuItem item = menu.add(0, IDM_FORMAT_BOLD, 0, "Bold"); item.setCheckable(true);

If there is a need to add several menu items with checkboxes or radio buttons, then you can combine them into menu groups by creating a separate identifier. The menu item is added to the group via the method add(), passing it the ID of the menu group as the first parameter. Let's say we declared IDs for the Color menu group and menu items to set the color:

Public static final int IDM_COLOR_GROUP = 400; public static final int IDM_COLOR_RED = 401; public static final int IDM_COLOR_GREEN = 402; public static final int IDM_COLOR_BLUE = 403;

Now to create a menu group with checkboxes, you need to assign a group ID to each menu item and call the method setGroupCheckable() for the entire group (in this case, there is no need to call the method setCheckable() for each menu item):

SubMenu subMenuColor = menu.addSubMenu("Color"); subMenuColor.add(IDM_COLOR_GROUP, IDM_COLOR_RED, Menu.NONE, "Red"); subMenuColor.add(IDM_COLOR_GROUP, IDM_COLOR_GREEN, Menu.NONE,"Green"); subMenuColor.add(IDM_COLOR_GROUP, IDM_COLOR_BLUE, Menu.NONE, "Blue"); subMenuColor.setGroupCheckable(IDM_COLOR_GROUP, true, false);

At the method setGroupCheckable() three options:

  • the first parameter is the menu group ID;
  • the second parameter is true if radio buttons or checkboxes are allowed in the group;
  • third parameter - sets single (true) or multiple (false) choice of menu items. This setting actually determines the appearance of the menu - it will be a menu with radio buttons or checkboxes.

    To control the state of checkboxes and radio buttons in the menu item selection event handler, write the following:

    @Override public boolean onOptionsItemSelected(MenuItem item) ( CharSequence message; switch (item.getItemId()) ( ... case IDM_COLOR_RED: // invert the state of the checkbox item.setChecked(!item.isChecked()); message = "Red color "; break; default: return false; )

    Run the project, call up the menu and select the menu item Color. You will have a submenu with three items (Red, Green, Blue) in the form of flags. The state of checkboxes and switches is processed in the program code and is saved when the menu is called again.

    You can immediately assign an intent to the selected menu item through the setIntent() method, which will fire when this item is clicked, if this event was not caught by the onMenuItemClickListener (deprecated) or onOptionsItemSelected handlers. Once triggered, the intent is passed to the startActivity method.

    MenuItem.setIntent(new Intent(this, MyOtherActivity.class));

    Programmatically opening or closing a menu

    If for some reason you need to programmatically open the menu (for example, for demonstration purposes), then use the method openOptionsMenu():

    OpenOptionsMenu();

    To programmatically close the menu, use the method closeOptionsMenu(), however, I have a repeated call to the method openOptionsMenu() also closes the menu.

    Programmatically removing a menu item

    Let's say we defined a menu item in an xml file:

    To remove an obviously unnecessary menu item from our cat program, we need to access the menu item through the method findItem() and make it invisible. A reference to the Menu object must be passed to the method onCreateOptionsMenu so that the program learns about the change in the composition of the menu.

    // class variable Menu menu; @Override public boolean onCreateOptionsMenu(Menu menu) ( super.onCreateOptionsMenu(menu); // pass a reference to our object this.menu = menu; getMenuInflater().inflate(R.menu.test, menu); return true; ) / / button click public void onClick(View v) ( if (menu != null) ( // find the desired item MenuItem item_dog = menu.findItem(R.id.action_dog); // make it invisible item_dog.setVisible(false); ) )

    But this decision there is a drawback, if we rotate the screen, the activity will be recreated and the remote menu will reappear. How can we get rid of the ugly dog?

    We need to remember the state of the menu item and store it in an object of type Bundle in the method onSaveInstanceState, and in the method onCreate() fetch saved state and pass to method onPrepareOptionsMenu, which is called before the menu is shown on the screen:

    Package en.alexanderklimov.test; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class TestActivity extends Activity ( Menu menu; Boolean savedMenuDogIsVisible; final static String KEY_MENU_DOG = "KEY_MENU_DOG"; @Override public void onCreate(Bundle savedInstanceState) ( super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); // retrieve menu item visibility data if (savedInstanceState != null) ( savedMenuDogIsVisible = savedInstanceState.getBoolean(KEY_MENU_DOG, true); ) ) @Override public boolean onCreateOptionsMenu(Menu menu) ( super.onCreateOptionsMenu(menu); this.menu = menu; getMenuInflater ().inflate(R.menu.test, menu); return true; ) public void onClick(View v) ( if (menu != null) ( MenuItem item_dog = menu.findItem(R.id.action_dog); // hide the menu item item_dog.setVisible(false); ) ) @Override protected void onSaveInstanceState(Bundle outState) ( // TODO Auto-generated method stub super.onSaveInstanceState(outState); if (menu != null) ( MenuItem item_dog = menu. findItem(R.id.action_dog); // save the current state of the menu item - true or false outState. putBoolean(KEY_MENU_DOG, item_dog.isVisible()); ) ) @Override public boolean onPrepareOptionsMenu(Menu menu) ( if (savedMenuDogIsVisible != null) ( MenuItem item_dog = menu.findItem(R.id.action_dog); // before displaying the desired state of the menu item_dog.setVisible(savedMenuDogIsVisible ); ) return super.onPrepareOptionsMenu(menu); ) )

    Detect presence of Menu button

    Older devices used a real Menu button. In new versions android menu removed in ActionBar and its presence as a separate button became optional. But many manufacturers still produce phones with a menu button. To determine if there is such a button, Android 14 added new method, which will determine the presence of this button.

    If(Build.VERSION.SDK_INT<= 10 || (Build.VERSION.SDK_INT >= 14 && ViewConfiguration.get(this) .hasPermanentMenuKey())) ( // menu key is present Toast.makeText(this, "Menu Button is", Toast.LENGTH_LONG).show(); ) else ( // No menu key Toast.makeText(this, "No Menu Button", Toast.LENGTH_LONG).show(); )

    Markup for the menu

    In modern devices, the menu is part of ActionBar. And you can customize the menu layout via XML.

    Let's say you chose this option:

    In attribute showAsAction don't use the value never, otherwise you won't see the markup. The markup itself is specified through the attribute actionLayout. Markup code:

    Menu in fragments

    A menu can be not only part of an activity, but also part of a fragment. The principle of operation is practically the same. The fragment has a corresponding method.

    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) ( super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.fragment_crime_list, menu); )

    FragmentManager responsible for the call onCreateOptionsMenu() when the activity receives a callback onCreateOptionsMenu() from the system. You must explicitly tell the manager FragmentManager that the fragment should get called onCreateOptionsMenu(). For this, the method is called setHasOptionsMenu():

    // In the fragment code @Override public void onCreate(Bundle savedInstanceState) ( super.onCreate(savedInstanceState); setHasOptionsMenu(true); getActivity().setTitle(R.string.cat); ... )

Prior to Honeycomb (Android 3.0), all Android devices had a "menu" button below the screen. Developers could use it as they saw fit, and many apps' interfaces were built around this button. The tablet-oriented Honeycomb has taken a step away from mechanical (and touch) buttons, and in this regard, in the third android versions the ActionBar class appeared, which made it possible to give the user fast access to the application settings through a special panel called the action bar. According to Google Developers Action Bar is the future and programmers should stop using the "menu" button. The market is currently dominated by smartphones with mechanical or touch button under the screen, but with the advent of Ice Cream Sandwich, the situation may change dramatically. It is important for you, as a developer, to prepare in advance for the appearance of such devices, and use the Action bar concept today.

At first glance, it may seem that using the Action Bar will cause problems when developing programs for Android 2.x, in which this bar has not yet been implemented. However, there is no problem here. Nobody forbids you to continue using the "menu" button on those devices where it is present, adding an Action Bar will require you to write only a few lines of code.

If I tried to condense this article into one sentence, it would be: " Set targetSdkVersion to 14, and tag showAsAction="ifRoom" on the menu items that should be rendered on the Action Bar".

The final rejection of the settings menu in Android

It's not enough to just stop using the "menu" button, you need to get the concept out of your head completely. Don't create menus, create all the necessary buttons directly inside the activities. If some actions do not fit on the panel, put them in an additional drop-down menu (action overflow). The above picture shows an action bar with a search button and an additional menu on the right side of the bar.

If your application is built for old version Android (which traditionally uses a menu), then when launched on an Android 3 tablet, a panel will be displayed at the bottom of the screen that emulates the three buttons that exist on the phones of the second branch.

The terminology is quite confusing, but the dropdown menu (action overflow) suggests a completely different concept of use than a simple settings menu. Instead of thinking of a menu as a repository for all of the application's settings, you create a panel where you put the main settings. Everything secondary is taken out in the drop-down menu, which is called when you click the button with three dots (Action overflow button) on the right side of the panel.

action overflow button

If you have run applications written for Android 2.3 and below on devices without buttons below the screen (for example, on a tablet with a Honeycomb or on a Galaxy Nexus), you may have noticed that an Action overflow button appears next to the image of three buttons on the panel at the bottom (three dots on top of each other). This is a compromise, but not a very good one. In applications that do not use the settings menu at all, this button does nothing, annoying users. Therefore, a very good solution would be to follow android version, and if your program runs under Android 3.0+, remove this button from the navigation bar and use the Action Bar. This approach allows you to keep the program compatible with old devices and make it more attractive to new ones.

If your program is running on devices without buttons, the system decides whether to add action overflow to the navigation bar depending on the value of the field in the manifest. The logic is as follows

  • If you set minSdkVersion or targetSdkVersion to a value greater than 11, then the system does not add this button.
  • On the other hand, the system creates this button when you run the application on Android 3.0 and above.
  • The only exception is when you set minSdkVersion to 10 or lower; targetSdkVersion to 11, 12 or 13 and will not use the ActionBar, the system will add this button on phones (not tablets) under Android control 4.0 and above. This exception is based on the following idea: if you are developing an application for phones of the second branch and for tablets of the third, then you assume that phones should have a menu button, but tablets do not.

Thus, if you want to disable the overflow action of a button in the navigation bar, you need to set the targetSdkVersion to 14 (You can write more than low value so that the program can run on older devices).

Transition to the action bar concept

If you have activities that use the options menu (created with onCreateOptionsMenu()), then by removing the button from the navigation bar (by setting targetSdkVersion=14) you should provide the user with an alternate means of accessing the options. Luckily, you don't have to do much work because the system automatically creates an action bar.

Add showAsAction="ifRoom" to your tags the elements you want to put in the action bar. If you're not sure which element to include in an Action Bar, see the Android Design's Action Bar guide .

To make the perception of your program more holistic, we recommend that you use icons from Android UX Team. Archive .

How to Remove Action Bar from Android Application

If you don't need the Action bar, you can remove it from any activity, or even from the application. This may be relevant for games and programs that do not use the settings menu. You can remove the action bar using Theme.Holo.NoActionBar or Theme.DeviceDefault.NoActionBar theme.

If you want to use these schemes but keep backwards compatible, you can use the resource management system to set different themes for different versions platforms. This topic is covered in more detail here. You will need to create your own theme that will inherit from themes various platforms depending on the current version.

For example, you can declare a theme for your application

(or for a specific activity in a tag ).

For devices running Android 2, include the following theme in res/values/themes.xml.



For Honeycomb, include the following theme in res/values-v11/themes.xml.



At startup, depending on the version of the API, the system will select the appropriate theme.

Conclusion

Let's recap the key ideas and points of the article:

  • On the new Android devices may not have a "menu" button, so when developing programs, it is better to refuse to use it at all.
  • Set targetSdkVersion = 14 and test your app on Android 4.0.
  • Add the showAsAction="ifRoom" tag to a menu item if you want it to automatically go to the action bar.
  • If your application does not use ActionBar, you can remove it using Theme.Holo.NoActionBar and Theme.DeviceDefault.NoActionBar themes.

Android supports several types of menus. First - there is a separate button on the phone Menu(in older phones), pressing which brings up the menu. In new devices, a separate button was removed, replacing it with a menu icon in three dots in vertical orientation. The second type is a context menu that appears when you press and hold your finger on the screen in right place(You can also press and hold the center button on your phone). Context menu in turn may have a submenu. Today we will get acquainted with the first type of menu. This article will cover working with the menu on new devices running Android 4.0 and higher.

In template empty activity there is no menu, so we will create it ourselves. This will help you understand how it works and get a general idea of ​​the project. It is not necessary to memorize the names of classes, methods, and code for handling the selection of menu items. In other templates, the menu will be built in and you can use it right away.

Create new project based empty activity and run it. There is no menu yet.

Create multiple string resources in a file res/values/strings.xml, which will be responsible for the menu items:

Settings Cat Cat Kitty

Now create a new folder menu in folder res res, | New | Directory). Next, create a file in the created folder menu_main.xml- the name indicates that the menu belongs to the main activity MainActivity(right click on the folder menu | New | Menu Resource File). If you create an application with multiple screens, then each activity will have a separate menu with its own settings. While opening the file menu_main.xml and add our code to the resulting template:

Let's open the file MainActivity. Right now it has only one method. onCreate(). Let's add a new method onCreateOptionsMenu(). Exactly this method is responsible for the appearance of the menu in the activity. Choose from the studio menu Code| and in the next window, start typing the name of the method in the first letters. Can be entered first capital letters, i.e. ocom( o n C rate O options M enu) to quickly find the desired string. We press the button OK and we get the workpiece.

@Override public boolean onCreateOptionsMenu(Menu menu) ( return super.onCreateOptionsMenu(menu); )

We add a method to the preparation that takes data from menu resources and converts them into menu items on the screen.

@Override public boolean onCreateOptionsMenu(Menu menu) ( getMenuInflater().inflate(R.menu.menu_main, menu); return true; )

In method inflate() you are pointing to a menu resource ( R.menu.menu_main) and class object Menu.

In English, "inflate" is translated as to inflate, i.e. by design android developers, we kind of inflate an object with data, for example, a menu. But in fact, the word "inflate" comes from the phrase flat- to the apartment. There is an old tradition to launch the first cat into the apartment, which explores all the nooks and crannies of the house and declares its consent to live in it. So we run the data from the XML file into the MenuInflater object.

Run the project. Now on the right side of the header you will see an icon of three dots arranged in vertical line. Click on the icon to see the menu item Settings.

As it is not difficult to guess, the element item is responsible for a separate menu item. Let's add three more items in the same way, changing only the identifier and text for the menu:

Run the project and try bringing up the menu again. You will see three new items.

Options id and title need no explanation. Parameter orderInCategory allows you to set your own menu item display order. Suppose you have created five menu items, but have not yet decided on the order in which they are displayed on the screen. In order not to constantly move entire blocks of code for menu items in right order, you can use this option.

And finally, an important attribute app:showAsAction defines the behavior of the menu in ActionBar. Meaning never means that the menu item should not be displayed in the header, but only in the popup menu, i.e. be behind the three dots. If you set the value always, then point Settings will immediately appear in the header of your application. Also available values ifRooms, withText and collapseActionView. Try it yourself. For example, ifRoom Displays a menu item if space permits. If there are a lot of points, then they will only get in the way. As a rule, this option displays a very short word or icon for frequent operations in order to avoid unnecessary clicks on three dots.

Notice the attribute app:showAsAction, which belongs to the namespace xmlns:app="http://schemas.android.com/apk/res-auto". There was a time when such a namespace did not exist and projects used the attribute android:showAsAction from the standard namespace. If the studio will swear at the error, then edit the code.

Until the menu items execute useful work. Any click on the item simply closes the menu without visible consequences. We haven't written the code to handle clicks yet.

Selecting menu items

We have learned how to create a menu. But so far it is useless, since the menu items do not react in any way to our clicks. Another method is used to handle menu clicks. onOptionsItemSelected(). Let's add a method in the same way as for the previous example. Let's get the preparation.

@Override public boolean onOptionsItemSelected(MenuItem item) ( return super.onOptionsItemSelected(item); )

Parameter item responsible for the menu item. You should get menu id via method getItemId() and enter a code for it. Since the menu usually consists of several items, it is convenient to use the constructions if/else or switch. To display information, we use a text label. Add a component to the activity screen textview. You can use the existing textview labeled "Hello World!", just give it an ID.

android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!"/>

Let's add the code to the blank for the selected menu item:

@Override public boolean onOptionsItemSelected(MenuItem item) ( // Get the ID of the selected menu item int id = item.getItemId(); TextView infoTextView = (TextView) findViewById(R.id.textView); // Operations for the selected menu item switch ( id) ( case R.id.action_cat1: infoTextView.setText("You chose a cat!"); return true; case R.id.action_cat2: infoTextView.setText("You chose a cat!"); return true; case R. id.action_cat3: infoTextView.setText("You have chosen a kitten!"); return true; default: return super.onOptionsItemSelected(item); ) )

Run the application, call up the menu and select any menu item. A message should appear in the text box.

Exists alternative way via XML similar to handling button clicks (since Android 3.0). You can add attribute android:onclick in menu resources and you don't need to use method call onOptionsItemSelected(). With help android:onclick you can specify the desired method when selecting a menu item. Add this attribute to the item Settings

Now in the activity code we will write the following:

// the Settings menu item attribute is set to android:onClick="onSettingsMenuClick" public void onSettingsMenuClick(MenuItem item) ( TextView infoTextView = (TextView) findViewById(R.id.textView); infoTextView.setText("You have selected Settings, better would choose a cat"); )

Switches

The appearance of the menu items can be changed to a view with radio buttons. To do this, add an element group with attribute android:checkableBehavior="single":

I don't see much point in this mode. And we will not consider it.

Design mode

Android Studio 2.2 added a graphical mode for building menus that look like a toolbar for adding new components to the screen. The menu bar consists of four elements: Menu Item, Search Item, Menu, group.

The principle is the same, select the desired element and drag it onto the screen into the menu area. If you have learned to manually create a menu, then this way won't cause you any trouble. With it, you can quickly sketch out the menu structure, and then tweak it manually.