Loading Menus Through XML Files

Up until this point, we've created all our menus programmatically. This is not the most convenient way to create menus because for every menu you have to provide several IDs and define constants for each of those IDs. You'll no doubt find this tedious.

Instead, you can define menus through XML files; you can do this in Android because menus are also resources. The XML approach to menu creation offers several advantages, such as the ability to name the menus, order them automatically, give them IDs, and so on. You can also get localization support for the menu text.

Follow these steps to work with XML-based menus:

1. Define an XML file with menu tags.

2. Place the file in the /res/menu subdirectory. The name of the file is arbitrary, and you can have as many files as you want. Android automatically generates a resource ID for this menu file.

3. Use the resource ID for the menu file to load the XML file into the menu.

4. Respond to the menu items using the resource IDs generated for each menu item.

We will talk about each of these steps and provide corresponding code snippets in the following sections.

0 0

Post a comment