articles

home / developersection / articles / android delete multiple selected items in listview

Android Delete Multiple Selected Items in Listview

Manoj Pandey 38772 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

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

    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

<?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="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;

 

public class 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

     private class 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

     public void remove(String object) {

          DataList.remove(object);

          notifyDataSetChanged();

     }

 

     // get List after update or delete

     public List<String> getMyList() {

          return DataList;

     }

 

     public void toggleSelection(int position) {

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

     }

 

     // Remove selection after unchecked

     public void removeSelection() {

          mSelectedItemsIds = new SparseBooleanArray();

          notifyDataSetChanged();

     }

 

     // Item checked on selection

     public void selectView(int position, boolean value) {

          if (value)

              mSelectedItemsIds.put(position, value);

          else

              mSelectedItemsIds.delete(position);

          notifyDataSetChanged();

     }

 

     // Get number of selected item

     public int getSelectedCount() {

          return mSelectedItemsIds.size();

     }

 

     public SparseBooleanArray getSelectedIds() {

          return mSelectedItemsIds;

     }

}

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

 

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns: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")

public class MainActivity extends Activity {

     List<String> myList;

     ListView listView;

     MyListViewAdapter adapter;

 

     @Override

     protected void 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 Class adapter = 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

     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

 

              }

 

              @Override

      public boolean onCreateActionMode(ActionMode mode, Menu menu) {

                   // TODO Auto-generated method stub

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

                   return true;

 

              }

 

              @Override

            public boolean onActionItemClicked(final ActionMode mode,

                        MenuItem item) {

                   // TODO Auto-generated method stub

                   switch (item.getItemId()) {

                   case R.id.selectAll:

                        //

                        final int 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");

                        return true;

                   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

               public void onClick(DialogInterface dialog, int which) {

                                  // TODO Auto-generated method stub

 

                             }

                        });

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

 

                             @Override

             public void 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();

                        return true;

                   default:

                        return false;

                   }

 

              }

 

              @Override

              public void onItemCheckedStateChanged(ActionMode mode,

                        int position, long id, boolean checked) {

                   // TODO Auto-generated method stub

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

              }

          });

     }

 

}

 

 

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