Build Menus in Android with Java and XML: Introduction

This entry is part 1 of 2 in the series Build Menus in Android with Java and XML

Build Menus in Android with Java and XML

App users love powerful options and features, but if they’re not well organized within your app’s interface, they might as well not even exist. Depending on what you’ve built, these options and features could affect the way that the app behaves, they could offer extensive customization options, or they could even tie into APIs, other apps, hardware capabilities, or other external technologies. But, they’ll have to be intuitive and organized to be at their best. That’s where proper menu design comes in.

When you are designing an app it is very important to design a sensible order and structure for the many options, features and settings that you plan to build. Obviously, your interface plays a pivotal role in your app’s performance; without it, your app would be nothing more than a disorganized collection of functions.

Menu items are a very old and famous user interface entity. Almost all users are comfortable using menus in their apps. Android provides an easy and flexible infrastructure to add menus in your app. It lets you create menus through XML resources or directly via code. Based on the menu item clicked, a certain action can be performed by your app. In this article, we are going to see how we can easily create menus and respond to menus using the Android API.

Creating a Menu Using XML

Let’s start by creating an Android project called MenuOptionsDemoProject, in which we are going to demonstrate menu creation via XML. Once we have created a project and created an activity in MenuOptionsDemoProject, we are ready to add a menu to it.

One way to create an options menu in Android is using the menu.xml resource file. To create menus using this method, you must create a menu directory in your resource directory. Create a file called my_menu.xml. Your directory structure should look as follows:

image001

Once you have created the file structure above, you can add the following code into your my_menu.xml file:


<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/open" android:icon="@drawable/openicon"

android:title="Open the file" />

<item android:id="@+id/save"

android:icon="@drawable/saveicon"

android:title="Save the file" />

</menu>

To create a menu resource, you have to employ the <menu> tag. You must create this XML item tag for each menu item that you want to show in your menu. There are a lot of attributes that you can specify within <menu> XML tag. Some of the most important ones are the id for the item and the title tag, which determines the text shown on the menu item. You can also specify the icon for the <menu> item to determine the graphic that’s visually associated with it’s respective menu option.

In the above XML, we have created two menu items: one for opening a file, and one for saving the file. We have given both of the items titles, and we’ve also given each an icon.

Once the menu resource file (my_menu.xml) is ready and has all the items you intend to add, you can use MenuInflater to override the function onCreateOptionsMenu. This function is supposed to fill the menu object with the desired menu items, but Android’s MenuInflater class helps you create menu items from the XML resource mentioned above. The code of our activity will be as follows:


import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuInflater;

public class MenuOptionsDemoProject 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) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.my_menu, menu);

return true;

}

}

Now if you run your activity and click on the menu button, you should be able to see your newly-created menu items, as shown below.

2

In case you are using Eclipse for development, you also have a helpful Android menu editor using, which you can use add menu items. Below, we just added one more menu item (one for closing the file) through Eclipse’s Android menu editor.

3

Creating a Submenu Using XML

Once we have created the single-level menu using XML, now let’s create a submenu using the same XML method. Suppose we want the user to have the of either saving or closing only the current file or saving or closing all the files. Using submenus in Android, we will provide these new options to the user.

We will have to update our my_menu.xml file to add sub menus. Below is the modified XML file:


<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/open"

android:icon="@drawable/openicon"

android:title="Open the file" />

<item android:id="@+id/save"  android:icon="@drawable/saveicon"   android:title="Save the file">

<menu>

<item android:id="@+id/savecurrent"

android:title="Save Current file" />

<item android:id="@+id/saveall"

android:title="Save All Files" />

</menu>

</item>

<item android:id="@+id/close" android:title="Close the file" android:icon="@drawable/closeicon">

<menu>

<item android:id="@+id/closecurrent"

android:title="Close Current file" />

<item android:id="@+id/closeall"

android:title="Close All Files" />

</menu>

</item>

</menu>

In the above XML, you can you can add a nested <menu> tag to create a sub menu. In the newly modified XML data, we’ve added menu tags in both of the original menu items.

Our code in onCreateOptionsMenu will not require any changes, as the MenuInflater will just use the newly-updated xml. This gives us the ability to build out multi-tier Android menu items quickly and easily with simple XML tags.

If we run the activity now and click on the menu button, we will first see the first level menu, as shown below.

4

Once the user clicks on the “Save the file” item, the submenu will be shown for the user to select one of the second-tier options, as shown below.

5

Performing Actions on Menu Selections

Now that we’ve completed our menu, we should write the code to respond to all possible menu selections. Whenever a menu item in the options menu of the Android activity is selected, the onOptionsItemSelected function of the activity is called. In order to respond the menu selections, we will have to override this function in our activity.

The code for onOptionsItemSelected is as follows:


@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.open:

showToast("Open Clicked");

return true;

case R.id.savecurrent:

showToast("Save current Clicked");

return true;

case R.id.saveall:

showToast("Save All Clicked");

return true;

case R.id.closecurrent:

showToast("Close current Clicked");

return true;

case R.id.closeall:

showToast("Close all Clicked");

return true;

default:

return super.onOptionsItemSelected(item);

}

}

public void showToast(String message)

{

Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);

toast.show();

}

In the above code, the selected menu item is passed to the function onOptionsItemSelected. Then, using the getItemId function on the menu item, we can find out which menu item was chosen.

Then, based on the menu item selected, we call the function showToast with the appropriate message. Here, you can put any code that you want to execute on the selection of that particular menu item.

So in case the “Close all” menu option is clicked, now we should see the following message displayed:

6

Creating a Menu Via Code

In case you cannot create the menu using XML for some reason, you can also add the menu items via the code itself. Suppose we want to add the same three menu items (“open the file,” “save the file,” “close the file”) via code. We will have to write the code of our onCreateOptionsMenu function as follows:


@Override

public boolean onCreateOptionsMenu(Menu menu) {

menu.add(1, 1, 0, "Open the file");

menu.add(1, 2, 1, "Save the file");

menu.add(1, 3, 2, "Close the file");

return true;

}

Now, our onCreateOptionsMenu function has the menu object which we can utilize to build out the desired menu. In the add function, you will have to pass the groupid, itemid, order, and title as the arguments. Once we have made the changes and run the activity, the menu should look like the following:

7

Conclusion

In this article, we saw that in Android we can easily create menus using two different methods. The menus can be defined as resources in XML files, which makes it very easy for us to change the menu items if needed. We can also create submenus if needed based on the types of options we want to provide in our Android application. If creating menus in XML is not suitable, you can add menu items in Java instead. Providing options and customizations to the user in your Android application is absolutely necessary if you want to make a useful Android app.

So have fun building powerful, extensible Android apps with simple, easily-editable menus.

Build Menus in Android with Java and XML

Build Menus in Android with Java and XML: Contextual and Popup Menus >>

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

No Reader comments

Comments on this post are closed.