Contextual Action Bar In android

android_learners_hub


android_learners_hub
Previous

Contextual Action Bar (CAB)

Contextual Action Bar (CAB) has advanced user interface then Floating context menu because the long press gesture is now used to select multiple items and one function can be performed on them simultaneously. By enlarge, a Contextual action bar (CAB) is a temporary action bar that overlays the app’s action bar for the duration of a particular sub-task. When a user enables this mode by selecting an item, a contextual action bar appears at the top of the activity with menu items. When the user press the default back arrow (that appear at  top-left side) or done the action then, contextual action bar disappears and the action mode is disabled. To invoke the contextual action mode in view 
1. user performs a long-click on the view 
2. user selects a checkbox or similar UI component within the view
We can invoke CAB upon one of two above events or both.

The application and behavior for each action depends upon following 2 designs:-

1.Contextual actions on individual, arbitrary views(like button , TextView etc.).

2.Contextual actions on groups of items(ListView, GridView etc.).

We will discuss both designs with example in this post. Let's start with the first,Enabling the contextual action mode for individual view(Button).

Step 1( in MainActivity.java) Create variable of action mode.
 private ActionMode mActionMode;

Step 2(in activity_main.xml) Create a button in activity and set its id.

Code for activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Button"/>

</LinearLayout>

Step 3(in contextual_action_bar.xml) Create menu folder in res. and then create contextual_action_bar.xml file to store menu items.

Code for contextual_action_bar.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/Contextual_1"
android:title="Help"
android:icon="@drawable/ic_help_"
app:showAsAction="ifRoom"
/>
<item
android:id="@+id/Contextual_2"
android:title="info"
android:icon="@drawable/ic_baseline_info_24"
app:showAsAction="ifRoom"
/>
<item
android:id="@+id/Contextual_3"
android:title="Delete"
android:icon="@drawable/ic_baseline_delete_24"
app:showAsAction="ifRoom"
/>
</menu>
Step 4 (in MainActivity.java) Implement the ActionMode.Callback interface. When you write the following code , a red color bulb(error sign) appears left click it , it will show context actions click on impelements methods callback methods will be automatically implemented.

private ActionMode.Callback actionModeCallback = new ActionMode.Callback()

Keep in mind: The contextual action bar is not necessarily associated with the app bar. They operate independently, even though the contextual action bar visually overtakes the app bar position.


Callback methods:- 

The first method is ‘onCreateActionMode’. This method is called once when the ActionMode is first created and is where we should set up the Menu. 

@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;
    }

Moving onto ‘onPrepareActionMode’, this method will be called anytime the CAB is invalidated. 

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false; // Return false if nothing is done
    }

Next up is the ‘onActionItemClicked’ method this method is called to handle click events (whenever one of your CAB’s MenuItems is clicked).

@Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_share:
                shareCurrentItem();
                mode.finish(); // Action picked, so close the CAB
                return true;
            default:
                return false;
        }
    }


Last but not least is ‘onDestroyActionMode’. This method is called whenever the user leaves the CAB or you call ‘finish()’ on the ActionMode.

@Override
    public void onDestroyActionMode(ActionMode mode) {
       mActionMode = null; // set null value to variable of ActionMode, that we created in step 1.
    }

Step 5 Set OnLongclick listener to button (individual view) and then call  startSupportActionMode(ActionModeCallback) to enable the contextual action mode .
         
          button.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mActionMode != null) {
                    return false;
                }
                mActionMode = startSupportActionMode(ActionModeCallback);
                return true;
            }
        });
    }

 Code for  MainActivity.java

package com.example.contextualaction_bar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private ActionMode mActionMode;// step 1

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

------ Step 5------- Start
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mActionMode != null) {
return false;
}
mActionMode = startSupportActionMode(ActionModeCallback);
return true;
}
})
;
}// Step 4 ----- start-------
private ActionMode.Callback ActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
mode.getMenuInflater().inflate(R.menu.contextual_action_bar, menu);
// to set Title on Contextual action bar(CAB)
mode.setTitle("Choose any:");
return true;
}

// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;// Return false if nothing is done
}

// It will be called when the user selects a contextual menu item.
// Handling click events.
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
String Title= (String) item.getTitle()
;
Toast.makeText(MainActivity.this, Title, Toast.LENGTH_SHORT).show();
// to disappear or close contextual bar after the action is performed.
mode.finish();
return false;
}
// Called when the user exits the action mode
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}

}
;
}



Output:-

Output of CAB

Output of CAB after long press on button

Output of CAB after selecting Menu item

Related Topics:-



android_learners_hub


Comments