Android, Xml

Contextual action bar in android | Context Menu in android

contextual action bar

contextual action bar

Context Menu

Android menu is an easy and flexible user interface component, which is used to handle a set of actions. Context menu povides a set of menu options when user perform long click on an Element. Most often context menu is used for items in a RecyclerView, GridView, or other view collections in which the user can perform direct actions on each item.

Android provides two different way of context menu :-

  1. Floating Menu
  2. Contextual action mode or Contextual action bar

In this article we will only discuss about contextual action bar in android and contextual action mode android examples.

Contextual action bar :

A contextual action bar appears at the top of the screen in place of the app bar or underneath the app bar, with action items that affect the selected view element(s). When a user enables this mode by selecting an item, a contextual action bar appears at the top of the screen to present actions the user can perform on the currently selected item(s).

1. Create a New Project :

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from templates to create an Contextual action bar in android using android studio.

2. Add Button to your activity_main.xml or main layout

Add Button to your main layout. 

<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Contextual action bar"/>

Now open res -> layout -> activity_main.xml  file and just implement the following xml code .

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Contextual action bar"/>

</RelativeLayout>

3. Define a XML menu resource file :

Create a menu resource file for the menu items, and assign an icon to each one.

context_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/notification"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_notifications_none_black_24dp"
        android:title="@string/notification"/>
    <item android:id="@+id/help"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_help_black_24dp"
        android:title="@string/help"/>
    <item android:id="@+id/setting"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="@string/setting"/>
    <item android:id="@+id/logout"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_power_settings_new_black_24dp"
        android:title="@string/logout"/>
</menu>

4. Set the long-click listener to the view :

Set the long-click listener to the view, it may be a item of a RecyclerView, ListView or any other view. In our case we are using a Button.

Now create an instance of ActionMode and Call startActionMode() within the setOnLongClickListener() method when the user performs a long tap on the view.

contextualbtn.setOnLongClickListener(new View.OnLongClickListener() {
            // Called when the user long-clicks on btn
            @Override
            public boolean onLongClick(View v) {
                if(mActionMode != null){
                    return false;
                }
                // Start the contextual action bar
                // using the ActionMode.Callback.
                mActionMode = Main3Activity.this.startActionMode(mActionModeCallback);
                v.setSelected(true);
                return true;
            }
        });

5. Implement the ActionMode.Callback interface to handle the ActionMode lifecycle :

Now here just implement the ActionMode.Callback interface to handle all the action mode lifecycle . Be carefull that before to startActionMode() in onCreate() implement the ActionMode.Callback .

public ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);
            return true;
        }
        // Called each time ActionMode is shown. Always called after
        // onCreateActionMode.
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false; // Return false if nothing is done
        }

        // Called when the user selects a contextual menu item
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Handle item click
            switch (item.getItemId()){
                case R.id.notification :
                    Toast.makeText(Main3Activity.this,"Notification", Toast.LENGTH_SHORT).show();
                    mode.finish();
                    return true;
                case R.id.help :
                    Toast.makeText(Main3Activity.this,"Help",Toast.LENGTH_SHORT).show();
                    mode.finish();
                    return true;
                case R.id.setting :
                    Toast.makeText(Main3Activity.this,"Setting",Toast.LENGTH_SHORT).show();
                    mode.finish();
                    return true;
                case R.id.logout :
                    Toast.makeText(Main3Activity.this,"Logout",Toast.LENGTH_SHORT).show();
                    mode.finish();
                    return true;
                default:
                    return false;

            }

        }

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

6. Now open your MainActivity.java and add following code :

MainActivity.java

package net.technxt.contextmenu;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private ActionMode mActionMode;

    Button contextualbtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        contextualbtn = (Button)findViewById(R.id.btn);

        contextualbtn.setOnLongClickListener(new View.OnLongClickListener() {
            // Called when the user long-clicks on btn
            @Override
            public boolean onLongClick(View v) {
                if(mActionMode != null){
                    return false;
                }
                // Start the contextual action bar
                // using the ActionMode.Callback.
                mActionMode = MainActivity.this.startActionMode(mActionModeCallback);
                v.setSelected(true);
                return true;
            }
        });

    }

    public ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);
            return true;
        }
        // Called each time ActionMode is shown. Always called after
        // onCreateActionMode.
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false; // Return false if nothing is done
        }

        // Called when the user selects a contextual menu item
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Handle item click
            switch (item.getItemId()){
                case R.id.notification :
                    Toast.makeText(MainActivity.this,"Notification", Toast.LENGTH_SHORT).show();
                    mode.finish();
                    return true;
                case R.id.help :
                    Toast.makeText(MainActivity.this,"Help",Toast.LENGTH_SHORT).show();
                    mode.finish();
                    return true;
                case R.id.setting :
                    Toast.makeText(MainActivity.this,"Setting",Toast.LENGTH_SHORT).show();
                    mode.finish();
                    return true;
                case R.id.logout :
                    Toast.makeText(MainActivity.this,"Logout",Toast.LENGTH_SHORT).show();
                    mode.finish();
                    return true;
                default:
                    return false;

            }

        }

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

}

Now run the project/app to test Contextual action bar in android through android device or any Emulator .

Leave a Reply

Created by Bhashkar Poddar

%d bloggers like this: