Creating a contextual menu bar ( contextual action mode ) for a listview in Android

July 25, 2012
By

The contextual menu bar (contextual action mode) is introduced in Android 3.0 ( HoneyComb ). A contextual menu bar is a horizontal bar displayed at the top of an activity and can contain various menu item actions. In the article titled  “Creating a contextual menu bar ( contextual action mode ) for a single view in Android ” , we have seen that, how to apply an action on a single view in the contextual action mode. In this article, we will see , how to apply an action on multiple views listed in a listview. In this application, an activity will be switched to contextual action mode when a list item is long pressed.

This application is developed in Eclipse 3.7.2 with ADT plugin of version 20.0.2 and Android SDK of version R20.0.1.


1. Create new Android Application Project namely “ContextualActionBarListView”

Create new Android Application

Figure 1 : Create new Android Application


2. Enter application launcher details

Enter application launcher details

Figure 2 : Enter application launcher details


3. Create a blank activity

Choose blank activity to create

Figure 3 : Choose blank activity to create


4. Enter MainActivity Details

Enter Main Activity Details

Figure 4 : Enter Main Activity Details


5. Update the file res/values/strings.xml


<resources>

    <string name="app_name">ContextualActionBarListView</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Main Activity</string>

    <string name="action1">Action1</string>
    <string name="action2">Action2</string>
    <string name="action3">Action3</string>

</resources>


6. Create new file res/menu/context_menu.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action1"
        android:title="@string/action1"
    />

    <item
        android:id="@+id/action2"
        android:title="@string/action2"
    />

    <item
        android:id="@+id/action3"
        android:title="@string/action3"
    />

</menu>


7. Update the file src/in/wptrafficanalyzer/contextualactionbarsingleview/MainActivity.java


package in.wptrafficanalyzer.contextualactionbarlistview;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

    String[] rivers = new String[]{
        "Indus",
        "Ganges",
        "Brahmaputra",
        "Jamuna",
        "Sutlej",
        "Kaveri",
        "Godavari"
    };

    MultiChoiceModeListener mMultiChoiceModeListener;

    @Override
    protected void onStart() {
        super.onStart();

        /** For contextual action mode, the choice mode should be CHOICE_MODE_MULTIPLE_MODAL */
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

        /** Setting multichoicemode listener for the listview */
        getListView().setMultiChoiceModeListener(mMultiChoiceModeListener);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Defining a multichoicemodelistener for the listview. */
        mMultiChoiceModeListener = new MultiChoiceModeListener() {

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
            }

            /** This will be invoked when action mode is created. In our case , it is on long clicking a menu item */
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                getMenuInflater().inflate(R.menu.context_menu, menu);
                return true;
            }

            /** Invoked when an action in the action mode is clicked */
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                Toast.makeText(getBaseContext(), "Applying "+ item.getTitle() + " on "+ getListView().getCheckedItemCount() + " Rivers \n" + getCheckedItems(), Toast.LENGTH_LONG).show();
                return false;
            }

            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            }
        };

        /** Defining array adapter to host the list of items */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice  , rivers);

        /** Setting array adapter for the listview */
        getListView().setAdapter(adapter);

    }

    /** Returning the selected rivers */
    public String getCheckedItems(){
        String selected_rivers="";
        SparseBooleanArray checkedItems = getListView().getCheckedItemPositions();
        for(int i=0,j=0;i<rivers.length;i++){
            if(checkedItems.get(i)){
                j++;
                selected_rivers += "\n" + j + "." + rivers[i];
            }

        }
        return selected_rivers;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


8. Application in execution

Main Acitivity , lists a set of rivers

Figure 5 : Main Acitivity , lists a set of rivers

 

Contextual Action bar appears on long clicking a listview item

Figure 6 : Contextual Action bar appears on long clicking a listview item


9. Download


10. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , ,

4 Responses to Creating a contextual menu bar ( contextual action mode ) for a listview in Android

  1. Sarav on December 30, 2012 at 3:31 am

    Hey, thanks for the many code samples. I have done this with a ListView that’s part of a Tab inside a ViewPager. But the problem I have is that I can swipe away to another tab while still having the Contextual Action Bar active. What’s the best way to dismiss the CAB if I swipe to another tab?

    I know I can detect the tab change by a ViewPager.OnPageChangeListener, but I’m not sure how to get hold of the CAB and dismiss it.

    Thanks.

  2. kelvinshen on January 21, 2013 at 6:14 pm

    Thanks for such a good example.
    But I have a problem still disturbing me. How can I highlight these checked items in listview?
    I would be grateful if you could offer your advice.

  3. Vinicius on July 31, 2013 at 10:28 am

    Exactly what I needed, thx so much bro!

  4. Avijit Apu on February 2, 2015 at 12:21 pm

    Thanks.But I have a question_How to add text content inside this Menu List.Can you tell how I will do it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner