Wednesday 4 March 2015

Contextual Action Bar

The contextual action bar (CAB) is a temporary action bar that overlays your app's current action bar while data is selected. It appears after the user long-presses on a selectable data item.

From here the user can:
  • Select additional data items by touching them.
  • Trigger an action from the CAB that applies to all highlighted data items. The CAB then automatically dismisses itself.
  • Dismiss the CAB via the navigation bar's Back button or the CAB's checkmark button. This removes the CAB along with all selection highlights.
Create new menu item xml inside our res/menu/  folder.


<?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>

Write a code to start action mode in any event
For example:

listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
 @Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
// Capture total checked items
 final int checkedCount = listView.getCheckedItemCount();
// Set the CAB title according to total checked items
mode.setTitle(checkedCount + " Selected");
// Calls toggleSelection method from ListViewAdapter Class
adapter.toggleSelection(position);
}
 
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
 switch (item.getItemId()) {
case R.id.item_delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = adapter.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
Model selecteditem = adapter.getItem(selected.keyAt(i));
// Remove selected items following the ids
adapter.remove(selecteditem);
}
   }
   // Close CAB
  mode.finish();
  return true;
  default:
  return false;
}
}
  @Override
  public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.contextual_menu, menu);
return true;
}
 
@Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
adapter.removeSelection();
}
  @Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
});

To get full Code   Click Here

output:








2 comments:

  1. This Post is very useful to lean about CAB android .. Thankyou..

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete