Define Menus in XML

Just like Android UI layouts, you can define application menus in XML, then inflate them in your menu's onCreate...() callback method. This makes your application code cleaner and separates more interface design into XML, which is easier to visualize.

To start, create a new folder in your project res/ directory called menu. This is where you should keep all XML files that define your application menus.

In a menu XML layout, there are three valid elements: <menu>, <group> and <item>. The item and group elements must be children of a menu, but item elements may also be the children of a group, and another menu element may be the child of an item (to create a Submenu). Of course, the root node of any file must be a menu element.

As an example, we'll define the same menu created in the Options Menu section, above. We start with an XML file named options_menu.xml inside the res/menu/ folder:

<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/new_game"

android:title="New Game" /> <item android:id="@+id/quit" android:title="Quit" />

Then, in the onCreateOptionsMenu() method, we inflate this resource using MenuInflater.inflate():

public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true;

The getMenuInflater() method returns the MenuInflater for our activity's context. We then call inflate(), passing it a pointer to our menu resource and the Menu object given by the callback.

While this small sample may seem like more effort, compared to creating the menu items in the onCreateOptionsMenu() method, this will save a lot of trouble when dealing with more items and it keeps your application code clean.

You can define menu groups by wrapping item elements in a group element, and create Submenus by nesting another menu inside an item. Each element also supports all the necessary attributes to control features like shortcut keys, checkboxes, icons, and more. To learn about these attributes and more about the XML syntax, see the Menus topic in the Available Resource Types document.

0 0

Post a comment