In this Section we will see how we can create CAB by using 2nd method of implemention. I have already described CAB and its one method in my previous post check here Creating Contextual Action Bar – CAB to read more.
In This Part we will learn how to Enable CAB when user performs a long press gesture on particular view. If you want to invoke the contextual action mode only when the user performs long press gesture on view like ListView or GridView, and want to perform batch actions on multiple selected items then you can implement this by following steps below:
Idea
1.)Create a project named CABPart2 and android studio or eclipse whatever environment you have.
2.) Implement the AbsListView.MultiChoiceModeListener and set it to your ViewGroup (e.g. ListView). In its callback methods, you can specify the actions for the contextual action bar, respond to click events on action items, and handle its callback events (Which are actually inherited from ActionMode.Callback interface). Call setChoiceMode() with the CHOICE_MODE_MULTIPLE_MODAL argument.
A MultiChoiceModeListener receives events for CHOICE_MODE_MULTIPLE_MODAL. It acts as the ActionMode.Callback for the selection mode and also receives onItemCheckedStateChanged(ActionMode, int, long, boolean) events when the user selects and deselects list items.
If you have you used Gmail or any other mail android app then I am sure you have tried to perform long gesture on mails to delete mails, so let’s develop same like example. Here we will enable contextual action mode whenever user performs long press gesture and we will display number of items selected.
Steps:
1.) Write following into your activity_main.xml layout
<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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:background="@android:color/background_light" > <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:choiceMode="multipleChoice"> </ListView> </RelativeLayout>
2.) Create and write following into row_list_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:layout_gravity="center_vertical" android:padding="5dp" android:background="@android:color/background_light" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="17sp" android:layout_marginLeft="10dp" android:text="Test" android:textStyle="bold" /> </LinearLayout>
3.) Create a contextual menu (contextual_menu.xml) in menu folder, this menu gets displayed as contextual action bar whenever user performs long press gesture and write following code:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/item_delete" android:icon="@android:drawable/ic_menu_delete" android:showAsAction="ifRoom|withText" android:title="Delete" android:titleCondensed="Delete"> </item> </menu>
4.) Write following into your MainActivity.java:
package com.example.cabpart2; import java.util.HashMap; import java.util.Set; import android.app.ListActivity; import android.content.Context; 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.view.ViewGroup; import android.widget.AbsListView.MultiChoiceModeListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends ListActivity { private String[] data = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten"}; private SelectionAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAdapter = new SelectionAdapter(this, R.layout.row_list_item, R.id.textView1, data); setListAdapter(mAdapter); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() { private int nr = 0; @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub return false; } @Override public void onDestroyActionMode(ActionMode mode) { // TODO Auto-generated method stub mAdapter.clearSelection(); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub nr = 0; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.contextual_menu, menu); return true; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.item_delete: nr = 0; mAdapter.clearSelection(); mode.finish(); } return false; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { // TODO Auto-generated method stub if (checked) { nr++; mAdapter.setNewSelection(position, checked); } else { nr--; mAdapter.removeSelection(position); } mode.setTitle(nr + " selected"); } }); getListView().setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub getListView().setItemChecked(position, !mAdapter.isPositionChecked(position)); return false; } }); } private class SelectionAdapter extends ArrayAdapter<String> { private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>(); public SelectionAdapter(Context context, int resource, int textViewResourceId, String[] objects) { super(context, resource, textViewResourceId, objects); } public void setNewSelection(int position, boolean value) { mSelection.put(position, value); notifyDataSetChanged(); } public boolean isPositionChecked(int position) { Boolean result = mSelection.get(position); return result == null ? false : result; } public Set<Integer> getCurrentCheckedPosition() { return mSelection.keySet(); } public void removeSelection(int position) { mSelection.remove(position); notifyDataSetChanged(); } public void clearSelection() { mSelection = new HashMap<Integer, Boolean>(); notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views v.setBackgroundColor(getResources().getColor(android.R.color.background_light)); //default color if (mSelection.get(position) != null) { v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));// this is a selected position so make it red } return v; } } }
Run and check below output.
OutPut:
Creating Contextual Action Bar – CAB
Action Bar Search View
Action Bar
Top 10 Android App Development Trends | 2020 Guide
5 Best Resources to Get Started with Android Nougat
Android Studio Introduction
Services – An Android Component
Applying MediaCodec On An Open Source Android Audio Player