Free Android app covering all aspects of addiction, including prevention and treatment

Using the contextual action mode for contextual menus in your apps: A tutorial

  • Written by  Clive

Contextual menus, action mode, Contextual Action Bars and other stuff!

Android Contextual Menus icon

So what’s this all about?

Well, it’s sort of about context menus but different.

It’s all about using the contextual action mode. This lets the user do stuff with the items that they have selected.

Enabling the contextual action mode, displays a Contextual Action Bar at the top of the screen. You can then place action items, which are like menu options, on this bar.

The user selects items from a list for example, chooses an action item and the action linked to that action item is performed on all of the selected items.

Here’s an example

Say you had a list of countries and you want the user to be able to select a couple of them to add to a database. This is where you could use the contextual action mode.

It enables the user to select one or more of the countries in the list. They can then select a Save action item, for example, and all the selected country items will be saved in the database.

The Contextual Action Bar

Android Contextual Menus diagram

Long-pressing a list item enables the action mode and displays the Contextual Action Bar

The contextual action bar (CAB) is a temporary Action Bar that displays over the current action bar while the user selects data. It pops up when the user long-presses a data item.

While it shows, the user can select (or de-select) other data items.

They can also select an action item to process the selected data items.

The contextual action bar disappears when the user is done with their selections.

This is what you’ll learn from this tutorial

We’ll show you how to:

  • Display a list of items
  • Set up and display a Contextual Action Bar
  • Place your action items on the contextual action bar
  • Let the user select a number of items in the list
  • Let the user choose one of your action items
  • Perform your action on those selected items

Let’s get started

Before we start, have you seen this tutorial? Using menus in your apps: a tutorial?

The contextual action mode has been available since Android 3.0. It’s the preferred method for showing contextual actions.

You should use floating context menus if you're supporting devices running anything lower than Android 3.0 (API level 11).

Contextual menus display options (or actions) that when selected, affect a specific item.

There are two ways that you can provide contextual actions to your user:

  • In floating context menus – these appear as lists of options in a floating window. The selected action is performed on one item at a time. For more on context menus, have a look at Using menus in your apps: a tutorial
  • In the contextual action mode – this displays a Contextual Action Bar at the top of the screen. Action items are displayed on the bar. The chosen action affects all of the selected items

When the Contextual Action Bar is showing, it means that the action mode is active. The user can then select and de-select any number of items.

The user disables the action mode when:

  • they press an action item
  • they press the Done button
  • they press the Back button
  • they deselect all the items

The Contextual Action Bar disappears when the action mode is disabled.

The Contextual Action Bar operates separately from the Action Bar.

There are two ways that you can use the contextual action mode:

  1. you can use contextual actions on individual views - use this if you want to use the action mode on single items
  2. you can use contextual actions on multiple items - use this design if you want the user to be able to select multiple items and perform an action on all of the selected items

We’re going for the second option.

Our tutorial will show you how to perform contextual actions on a number of selected items at the same time

Our tutorial app

Our app displays a list of country names.

Long-press any item and a Contextual Action Bar (CAB) appears at the top of the screen. The user can select (or de-select) any number of items while the CAB is displayed.

The CAB contains two actions. One is displayed as an icon and the other as text. Press either and the defined action is applied to all of the selected items.

Android Contextual Menus overflow Menu

The overflow menu

There is also an overflow menu. Pressing the Overflow menu button displays the overflow menu

Selecting the menu item displays a sub menu. Selecting one of these options adds another option to the menu. Selecting the new option removes it from the menu.

It’s all in the list

There’s a list of countries that the user can select from:

Android Contextual Menus list screenshot

Long-pressing an item displays the Contextual Action Bar. The user can then select multiple items

We're using an array for our list. The list is displayed in a list view in our activity.

Here’s the code for defining the list view in the menu resource file, my_cab_menu.xml:

Android contextual action bar listview xml

We define the list view in the activity's layout file

We use an ArrayAdapter to get the list items out of the array to display in the list. Here’s the code:

Android CAB listview ArrayAdapter

Create a list view and an adapter and then link the adapter to the list view

Note the following:

  • findViewById - we get our list view in the activity layout file and assign it to our list view object, myListView
  • myArrayAdapter - this is our adapter that we'll use to populate the list view. It has three parameters:
    • the context
    • the layout that we use for each of the items that are displayed in the list view. We're using one of Android's standard list layouts, android.R.layout.simple_list_item_multiple_choice. It enables us to select more than one item at a time
    • the array that we use to populate the list
  • setAdapter - we attach the adapter to the list view to display the items

You may want to have a look at our Android ListView tutorial for how to use lists in your app.

Listen up! Listening for the selections

The MultiChoiceModeListener handles the item selections and de-selections. It only works if we set the choice mode to allow choices in a modal selection mode:

Android CAB setChoiceMode

Set the choice mode to allow multiple selections in the modal selection mode then set the MultiChoiceModeListener to the list view

The MultiChoiceModeListener includes a number of methods:

  • onItemCheckedStateChanged() - called when an item is checked or unchecked
  • onCreateActionMode() - called when the action mode is first created. You supply it a menu and it generates the action buttons for the action mode
  • onPrepareActionMode() - it's called to refresh the action mode's action menu whenever it is invalidated
  • onActionItemClicked() - called each time the user clicks an action button
  • onDestroyActionMode() - called when the action mode is about to be exited and destroyed

Make your choice: Selecting an item from the list

Once the Contextual Action Bar is showing, the user can select and de-select items. onItemCheckedStateChanged() is called each time a selection or de-selection is made.

This is what the code looks like:

Android contextual action mode onItemCheckedStateChanged

onItemCheckedStateChanged is called each time an item is selected or de-selected

Note the following:

  • we set the action mode title that is displayed in the Contextual Action Bar
  • getCheckedItemCount - we use this to get the latest number of items that have been checked. This number changes as items are selected and de-selected. We display the total along with the action mode title

Action stations! Creating the action mode

When the user long-clicks an item, onCreateActionMode() is called and the Contextual Action Bar is displayed.

Here’s the code:

Android contextual action mode onCreateActionMode

onCreateActionMode is called when the action mode is first created. This is where you inflate your menu

Note the following:

  • inflater - this is our menu inflater which we'll use to inflate our contextual action mode menu
  • inflate - we inflate our menu resource. It's saved as my_cab_menu.xml in the res/menu folder
  • setVisible - we don't want to show menu item Four at this stage so we set its visibility to false here

Changed your clothes? Freshen up and get ready to dazzle!

Each time you modify the menu, you must call invalidate(). This will ensure that onPrepareActionMode() is called to refresh the menu so that the modified menu is displayed.

Here’s the code:

Android contextual action mode onPrepareActionMode

onPrepareActionMode is called whenever the action mode's action menu is invalidated. Put any changes that you want to make to the menu here. The menu will be refreshed and the latest menu displayed

Note the following:

  • we use an if/else statement to set the visibility of menu Four. Its visibility depends on the value of the two booleans, isAddFour and isRemoveFour

Actually doing it: Handling the action item clicks

Once the user has selected all their items, they choose an action item on the contextual action bar. The onActionItemClicked() method decides which action to perform.

This is what part of the code looks like:

Android contextual action mode onActionItemClicked

onActionItemClicked is called each time the user clicks an action item

Note the following:

  • this is where we can execute code for each of the action mode's menu actions
  • we use a switch statement to filter the clicked action items. The code contained in the matching case statement is executed
  • R.id.cab_one - this is the ID of menu item One. It's executed when item One is selected. We call the doSomethingWithActionOneItems() method to do something with the selected items
  • finish - finishes and closes this action mode. OnDestroyActionMode() will then be called

Making changes: Adding and removing menu item Four

Android contextual action mode invalidate()

Clicking menu item Three invalidates the action mode causing the menu to refresh. Menu item Four will then show in the overflow menu

Android contextual action mode invalidate()

Clicking menu item Four invalidates the action mode causing the menu to refresh. Menu item Four will then be removed from the overflow menu

Note the following:

  • these are two of the options in the onActionItemClicked switch statement. Both are menu items appearing in the overflow menu
  • R.id.cab_three - this is menu item Three. We set the booleans here and call invalidate()
  • invalidate - calling invalidate() causes onPrepareActionMode() to be called. This updates the menu and depending on the values of isAddFour and isRemoveFour, sets the visibility of menu item Four accordingly
  • R.id.cab_four - this is menu item Four. We set the booleans here and call invalidate()

It’s all over: Destroying the action mode

onDestroyActionMode() is called when the action mode is about to be exited and destroyed. This happens when the user:

  • presses an action item
  • presses the Done button
  • presses the Back button
  • deselects all the items

Here’s the code:

Android contextual action mode onDestroy

onDestroyActionMode is called when the action mode is about to be destroyed

Note the following:

  • onDestroyActionMode is called when the action mode is about to be destroyed
  • we set both booleans to false here

Doing something with the selected items

Once the user has selected all their items, they choose an action item on the contextual action bar. This action item executes some code which does something with the selected items (it could delete these items from a database for example).

Our action item simply lists the selected items in the logcat.

Here’s the code for action item One:

Android contextual action mode performing the action

This method displays the selected countries in the logcat

Note the following:

  • This is our method which we use to do something with the selected items after action item One was clicked. We display the selected items in the logcat. If you’re interested, have a look at Using Android’s Log class API to debug Android application code for more on the logcat
  • checked – our Sparseboolean array object. It contains a key and a value. We’ll use the key as the index for our items in the list view. The value can be either true or false. True means that the item was selected
  • getCheckedItemPositions – returns a set of checked items (a Sparseboolean array of key (indexes)/values (true) for the checked items). Our adapter does not have stable id’s. This means that the id’s do not remain the same if the items in the array changes. If we had used items from a database to populate a CursorAdapter for example, then these id’s would be stable – they would remain the same for each item even if new items were added to the database or some items deleted. In this case, we could then use getCheckedItemIds() which would return an array (long[]) of id’s of all the checked items. We could then use these id’s to get the items out of the database
  • getItemAtPosition - we iterate through the checked array and if the item has a value of true, we retrieve the country item associated with the position identified by the key in the Sparseboolean array
  • we display the key and the selected country in the logcat

The action item Two triggers the doSomethingWithActionTwoItems() method which is the same as the one above.

I hope that you have found this tutorial helpful.

You may also be interested in this eBook, Android fragments, Action Bar, Menus, Notifications and Tabs.

This tutorial was created using Android Studio. You can download the project files here Download icon

Are you using Eclipse or another IDE? Here's how you can use this project's Android Studio files.