articles

Home / DeveloperSection / Articles / Android Delete Multiple Selected Items in Listview

Android Delete Multiple Selected Items in Listview

Manoj Pandey38493 13-Feb-2015

Previously, we learn about how to implement drag and drop control event in Android (Drag and Drop Event in Andriod). Now we see how to delete multiple on multiple selection in Listview. 

In android, you can delete multiple items from list.

In this Article, you will learn how to delete multiple selected items in your listview using a contextual action bar. User can select multiple item, first time long click and after just click.

1.      Create a new project in Eclipse. You need to target Android 3.2 or better.

2.      Add listView in activity_main.xml

 <RelativeLayoutxmlns: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"

    tools:context=".MainActivity">

 

    <ListView

        android:id="@+id/listview"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content">

    </ListView>

 

</RelativeLayout>

  3.      Create an XML graphical layout for your listview item

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

      android:background="?android:attr/activatedBackgroundIndicator"

    android:orientation="horizontal">

 

    <ImageView

        android:id="@+id/myImage"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:src="@drawable/ic_launcher"/>

 

    <TextView

        android:id="@+id/textview"

        android:layout_marginLeft="5sp"

        android:layout_gravity="center"

        android:textSize="20sp"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"/>

 

</LinearLayout>

 4.      Add adapter class for bind data in custom listview

 

package com.example.listviewmultipledeletion;

 

import java.util.List;

 

import android.content.Context;

import android.util.SparseBooleanArray;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ArrayAdapter;

import android.widget.ImageView;

import android.widget.TextView;

 

publicclass MyListViewAdapter extends ArrayAdapter<String> {

     Context myContext;

     LayoutInflater inflater;

     List<String> DataList;

     private SparseBooleanArray mSelectedItemsIds;

 

     // Constructor for get Context and list

      public MyListViewAdapter(Context context, int resourceId, List<String> lists) {

          super(context, resourceId, lists);

          mSelectedItemsIds = new SparseBooleanArray();

          myContext = context;

          DataList = lists;

          inflater = LayoutInflater.from(context);

     }

 

     // Container Class for item

     privateclass ViewHolder {

          TextView tvTitle;

          ImageView myImg;

     }

 

     public View getView(int position, View view, ViewGroup parent) {

          final ViewHolder holder;

          if (view == null) {

              holder = new ViewHolder();

              view = inflater.inflate(R.layout.listview_item, null);

              // Locate the TextViews in listview_item.xml

          holder.tvTitle = (TextView) view.findViewById(R.id.textview);

 

              // Locate the ImageView in listview_item.xml

          holder.myImg = (ImageView) view.findViewById(R.id.myImage);

              view.setTag(holder);

          } else {

              holder = (ViewHolder) view.getTag();

          }

          // Capture position and set to the TextViews

          holder.tvTitle.setText(DataList.get(position).toString());

 

          // Capture position and set to the ImageView

          holder.myImg.setImageResource(R.drawable.ic_launcher);

          return view;

     }

 

     @Override

     publicvoid remove(String object) {

          DataList.remove(object);

          notifyDataSetChanged();

     }

 

     // get List after update or delete

     public List<String> getMyList() {

          returnDataList;

     }

 

     publicvoid toggleSelection(int position) {

          selectView(position, !mSelectedItemsIds.get(position));

     }

 

     // Remove selection after unchecked

     publicvoid removeSelection() {

          mSelectedItemsIds = new SparseBooleanArray();

          notifyDataSetChanged();

     }

 

     // Item checked on selection

     publicvoid selectView(int position, boolean value) {

          if (value)

              mSelectedItemsIds.put(position, value);

          else

              mSelectedItemsIds.delete(position);

          notifyDataSetChanged();

     }

 

     // Get number of selected item

     publicint getSelectedCount() {

          returnmSelectedItemsIds.size();

     }

 

     public SparseBooleanArray getSelectedIds() {

          returnmSelectedItemsIds;

     }

}

 5.      Add menu for show contextual action bar after select item

 

<?xmlversion="1.0"encoding="utf-8"?>

<menuxmlns:android="http://schemas.android.com/apk/res/android">

   

     <item

        android:id="@+id/selectAll"

       

        android:title="Select All"/>

  <item

        android:id="@+id/delete"

       

        android:title="Delete"/>

</menu>

 6.      Now paste following code in MainActivity class

 

package com.example.listviewmultipledeletion;

 

import java.util.ArrayList;

import java.util.List;

 

import android.os.Bundle;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.content.DialogInterface.OnClickListener;

import android.util.SparseBooleanArray;

import android.view.ActionMode;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.AbsListView.MultiChoiceModeListener;

import android.widget.ListView;

 

@SuppressLint("NewApi")

publicclass MainActivity extends Activity {

     List<String> myList;

     ListView listView;

     MyListViewAdapter adapter;

 

     @Override

     protectedvoid onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);

          setContentView(R.layout.activity_main);

          myList = new ArrayList<String>();

          // Add item in list

          for (int i = 1; i < 81; i++)

              myList.add("Item " + i);

          listView = (ListView) findViewById(R.id.listview);

          // Pass value to MyListViewAdapter Classadapter = new MyListViewAdapter(this, R.layout.listview_item, myList);

          // Binds the Adapter to the ListView

          listView.setAdapter(adapter);

          // define Choice mode for multiple delete

          listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

  listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

 

              @Override

     publicboolean onPrepareActionMode(ActionMode mode, Menu menu) {

                   // TODO Auto-generated method stub

                   returnfalse;

              }

 

              @Override

              publicvoid onDestroyActionMode(ActionMode mode) {

                   // TODO Auto-generated method stub

 

              }

 

              @Override

      publicboolean onCreateActionMode(ActionMode mode, Menu menu) {

                   // TODO Auto-generated method stub

         mode.getMenuInflater().inflate(R.menu.multiple_delete, menu);

                   returntrue;

 

              }

 

              @Override

            publicboolean onActionItemClicked(final ActionMode mode,

                        MenuItem item) {

                   // TODO Auto-generated method stub

                   switch (item.getItemId()) {

                   case R.id.selectAll:

                        //

                        finalint checkedCount = myList.size();

             // If item is already selected or checked then remove or

                        // unchecked and again select all

                        adapter.removeSelection();

                        for (int i = 0; i < checkedCount; i++) {

                             listView.setItemChecked(i, true);

                             // listviewadapter.toggleSelection(i);

                        }

                 // Set the CAB title according to total checked items

 

            // Calls toggleSelection method from ListViewAdapter Class

 

                        // Count no. of selected item and print it

                        mode.setTitle(checkedCount + " Selected");

                        returntrue;

                   case R.id.delete:

                // Add dialog for confirmation to delete selected item

                        // record.

               AlertDialog.Builder builder = new AlertDialog.Builder(

                                  MainActivity.this);

      builder.setMessage("Do you want to delete selected record(s)?");

 

               builder.setNegativeButton("No", new OnClickListener() {

 

                             @Override

               publicvoid onClick(DialogInterface dialog, int which) {

                                  // TODO Auto-generated method stub

 

                             }

                        });

             builder.setPositiveButton("Yes", new OnClickListener() {

 

                             @Override

             publicvoid onClick(DialogInterface dialog, int which) {

                                  // TODO Auto-generated method stub

                               SparseBooleanArray selected = adapter

                                           .getSelectedIds();

                  for (int i = (selected.size() - 1); i >= 0; i--) {

                                      if (selected.valueAt(i)) {

                                      String selecteditem = adapter

                                          .getItem(selected.keyAt(i));

                          // Remove selected items following the ids

                                        adapter.remove(selecteditem);

                                      }

                                  }

 

                                  // Close CAB

                                  mode.finish();

                                  selected.clear();

 

                             }

                        });

                        AlertDialog alert = builder.create();

                alert.setIcon(R.drawable.questionicon);// dialog Icon

                      alert.setTitle("Confirmation"); // dialog Title

                        alert.show();

                        returntrue;

                   default:

                        returnfalse;

                   }

 

              }

 

              @Override

              publicvoid onItemCheckedStateChanged(ActionMode mode,

                        int position, long id, boolean checked) {

                   // TODO Auto-generated method stub

            finalint 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);

              }

          });

     }

 

}

 

 

Now run your application

Android Delete Multiple Selected Items in Listview

After selected item 

Android Delete Multiple Selected Items in Listview

On Select All 


Updated 14-Jul-2020

Leave Comment

Comments

Liked By