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

July 25, 2012
By

Beginning with Android 3.0, a new UI feature is introduced which is called contextual action mode. In this mode, a contextual menu will be displayed at the top of the screen in a horizontal bar with a set of menu actions. These menu actions can be acted on a single view of an activity or on multiple items of a listview or gridview. In this application we are going to explain how to create a contextual menu bar for a single view.

In order to create  a contextual action mode in Android 2.x and above , see the article titled “Creating Contextual Action Mode for single views in pre Honeycomb versions using Sherlock Library

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


1. Create new Android Application Project namely “ContextualActionBarSingleView”

New Android Project

Figure 1 : New Android Project


2. Enter application launcher details

Input launcher details of the application

Figure 2 : Input launcher details of the application


3. Create a blank activity

Select Activity Type

Figure 3 : Select Activity Type


4. Enter MainActivity Details

Input Main Activity Details

Figure 4 : Input Main Activity Details


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

<resources>

    <string name="app_name">Contextual ActionBar SingleView</string>
    <string name="hello_world">Hello, Long Press Me !!!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Main Activity</string>

    <string name="str_action1">Action1</string>
    <string name="str_action2">Action2</string>
    <string name="str_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/str_action1"
    />

    <item
        android:id="@+id/action2"
        android:title="@string/str_action2"
        android:icon="@android:drawable/btn_star"
    />

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

7. Update the file res/layout/activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />

</RelativeLayout>


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

package in.wptrafficanalyzer.contextualactionbarsingleview;

import android.app.Activity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    ActionMode.Callback mCallback;
    ActionMode mMode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tvHello = (TextView) findViewById(R.id.tv_hello);

        mCallback = new ActionMode.Callback() {

            /** Invoked whenever the action mode is shown. This is invoked immediately after onCreateActionMode */
            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            /** Called when user exits action mode */
            @Override
            public void onDestroyActionMode(ActionMode mode) {
                mMode = null;
            }

            /** This is called when the action mode is created. This is called by startActionMode() */
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                mode.setTitle("Demo");
                getMenuInflater().inflate(R.menu.context_menu, menu);
                return true;
            }

            /** This is called when an item in the context menu is selected */
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                switch(item.getItemId()){
                case R.id.action1:
                    Toast.makeText(getBaseContext(), "Selected Action1 ", Toast.LENGTH_LONG).show();
                    mode.finish();    // Automatically exists the action mode, when the user selects this action
                    break;
                case R.id.action2:
                    Toast.makeText(getBaseContext(), "Selected Action2 ", Toast.LENGTH_LONG).show();
                    break;
                case R.id.action3:
                    Toast.makeText(getBaseContext(), "Selected Action3 ", Toast.LENGTH_LONG).show();
                    break;
                }
                return false;
            }
        };

        OnLongClickListener listener = new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                if(mMode!=null)
                    return false;
                else
                    mMode = startActionMode(mCallback);
                return true;
             }
        };

        tvHello.setOnLongClickListener(listener);

    }

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


9. Application in execution

Main Activity of the application

Figure 5 : Main Activity of the application

 

Contextual Menus in the Contextual Action Mode

Figure 6 : Contextual Menus in the Contextual Action Mode


10. Download


11. 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: , ,

3 Responses to Creating a contextual menu bar ( contextual action mode ) for a single view in Android

  1. Jayesh on April 24, 2013 at 3:07 am

    Nice and easy to understand tutorial. Useful at this point as I was learning the same :)
    Thanks.

  2. Gustavo on February 26, 2014 at 7:02 pm

    It’s good because you don’t add a lot of unnecessary text, and the shading on the important lines help us to understand the code. Maybe you could add just a bit of explanation to unite the information from the code.
    Thank you for the tutorial.

  3. Avs on February 22, 2015 at 1:17 pm

    How is the Colour of ActionBar getting changed on LongClick?

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