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

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

Build Menus in Android with Java and XML

In the previous article in this series, we learned how to create standard options menus for your Android app using XML or built directly through Java programming. Besides these typical options menus, Android developers can also create specialized menu types such as the contextual menu and the popup menu within their Android apps.

A contextual menu is a menu which affects (or appears on) specific items and generally has options that affect only that particular item. The contextual menu in Android appears when a user presses and holds on a specific item. The contextual menu will be presented to the user, and he or she will be able to choose from the array of options.

Android also lets you create popup menus in your application. A popup menu is a modal menu that can be programmed to appear when a button is clicked.

In this article, we are going to demonstrate how we can create contextual and popup menus within our Android apps.

Registering the View for Contextual Menus

To start, we are going to build a basic example by creating a contextual menu on one single item. A contextual menu is created within a view, so we will register that view for the contextual menu first and then move on to the menu itself.

Bu, lets first create an Android activity within layout main.xml file as follows:


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

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

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical"

>

<TextView

android:id="@+id/<span style="text-decoration: underline;">Username</span>"

android:layout_width="fill_parent"

android:layout_height="60dip"

android:text="Hold For contextual menu"

android:padding="4dip"

/>

<EditText

android:id="@+id/usernameEdittext"

android:layout_height="wrap_content"

android:singleLine="true"

android:background="#<span style="text-decoration: underline;">ffffff</span>"

android:layout_width="400dip" >

</EditText>

</LinearLayout>

In the above layout, we have just created one TextView and one edit view within the layout. Now, we’ll write the code for the activity is as follows:


package com.contexualandpopupmenudemon;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.widget.EditText;

public class ContextualAndPopupmenuDemo extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

EditText UserNameEditText = (EditText)findViewById(R.id.usernameEdittext);

registerForContextMenu(UserNameEditText);

}

}

In the activity above, we have overridden the onCreate method in which we have set the main layout. Then, we find the EditText using the function findViewById.

Once we get the EditView, we call registerForContextMenu on that view. This function registers the view and allows us to display a context menu.

Creating the Contextual Menu

Once we have registered the view for a contextual menu, we will create a menu in XML for our contextual menu. To create a menu in XML format, create a contextual.xml file in the menu folder of your resources. Add the following code to your contextual.xml file:


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

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

android:title="Fetch New <span style="text-decoration: underline;">Username</span>" />

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

android:title="Check For Duplicate" />

</menu>

In our contextual menu, we have created two items: one to acquire usernames, and one to check for duplicates. Once we have created the menu in XML format, we will have to override the onCreateContextMenu function as follows:


@Override

public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

if (v.getId()==R.id.usernameEdittext) {

getMenuInflater().inflate(R.menu.contextual, menu);

}

}

In this code, we determine if the ID of the view is the specific one we are looking for. If it is, we initiate the menu as described in the previous article in this series.

Now, if you hold for a few seconds on the EditText, you should be able to see the following contextual menu:

image001

If you don’t want to build this menu in XML, you can build an identical menu in Java using the following programming:


@Override

public void onCreateContextMenu(ContextMenu menu, View v,

ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

if (v.getId()==R.id.usernameEdittext) {

menu.add(0, 1, 0, "Fetch New Username");

menu.add(0, 2, 0, "Check For Duplicate");

}

}

Now, if you run the app again, you will see a very similar menu to what we created through XML formatting.

Responding to Clicks on Contextual Menus

To respond to user selections on our contextual menus, we must implement the onContextItemSelected function within our activity. To respond to our menu items, we implement the onContextItemSelected as shown below:


@Override

public boolean onContextItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.fetch:

showToast("Fetch Clicked");

return true;

case R.id.check:

showToast("Check Clicked");

return true;

default:

return super.onContextItemSelected(item);

}

}

public void showToast(String message) {

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

toast.show();

}

In the programming above the menu item that’s chosen is passed to the function onContextItemSelected, and we can call getItemId to identify which menu item was clicked. Then, we call the appropriate function (that matches the user’s choice) to handle this menu click . Currently, the only functionality that results from selecting a menu option is a toast with a message. So, now if you click on the “Fetch New Username” option, you should see the following:

image003

Creating a Popup Menu

A popup menu (supported only after Android API level 11) is a modal menu that you can create and display near a view. For demonstration purposes, we will create a popup menu when an “Options” button is clicked on the activity. First, let’s add this “Options” button to our layout.xml file, as shown below.


<Button

android:id="@+id/<span style="text-decoration: underline;">btnoptions</span>"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Options"

android:onClick="CreatePopupMenu"/>

This will create the necessary “Options” button for our popup menu. When selected, the function CreatePopupMenu will be called. Then, we create a new popup.xml file in our res/menu folder with the following content:


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

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

android:title="Option 1" />

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

android:title="Option 2" />

</menu>

In our popup.xml file above, we have created two menu items: option1, and option2. Then, we add the function CreatePopupMenu to our activity using the following programming:


public void CreatePopupMenu(View v) {

PopupMenu mypopupmenu = new PopupMenu(this, v);

MenuInflater inflater = mypopupmenu.getMenuInflater();

inflater.inflate(R.menu.<i>popup</i>, mypopupmenu.getMenu());

mypopupmenu.show();

}

Above, we create a new PopupMenu object and then include our popup.xml menu within it. Then, we show the popup menu by calling the show function.

So, now if we run the app and click on our new “Options” button, you should be able to see the menu shown below.

image005

Responding to Popup Menu Clicks

To respond to popup menu clicks, you have to set a menu item click listener, which is a class that implements the OnMenuItemClickListener interface. It has one method in it—onMenuItemClick. We will implement this interface in our activity itself. So, we must change the class definition as follows:


public class ContextualAndPopupmenuDemo extends Activity implements OnMenuItemClickListener{

Then we change CreatePopupMenu and implement onMenuItemClick as follows

public void CreatePopupMenu(View v) {

PopupMenu mypopupmenu = new PopupMenu(this, v);

mypopupmenu.setOnMenuItemClickListener(this);

MenuInflater inflater = mypopupmenu.getMenuInflater();

inflater.inflate(R.menu.popup, mypopupmenu.getMenu());

mypopupmenu.show();

}

@Override

public boolean onMenuItemClick(MenuItem arg0) {

switch (arg0.getItemId()) {

case R.id.option1:

showToast("Option1 Clicked");

return true;

case R.id.option2:

showToast("Option2 Clicked");

return true;

default:

return super.onContextItemSelected(arg0);

}

}

In the function, onMenuItemClick—depending on the menu item clicked—will display the appropriate toast. If we click on one of the menu options, we should see the toast shown below.

image008

Conclusion

In Android, you can create a wide variety of menus for various settings and circumstances. You can define those menus in an XML file, or you can add them via java code directly. You can respond to the menu items depending on the type of menu (contextual, popup) you have created. When you offer application-wide settings, you should typically use the “Options” menu. If you want to offer specialized options or settings for a particular item, then you probably should use the contextual menu.

For the contextual menu to appear, the user has to hold for some time on the desired option. If you want to show a menu on some other user action such as a click of a button or tapping an image, you can use popup menu for that purpose as well. Regardless of your app idea or the functionality that you have in mind, you now have the tools needed to capture user input and build a sensible, intuitive app experience. Have fun while implementing these various menu types in your next Android app.

Build Menus in Android with Java and XML

<< Build Menus in Android with Java and XML: Introduction

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments