Android Delete Multiple Selected Items In ListView Tutorial
Last Updated: October 13, 2013
In this tutorial, you will learn how to delete multiple selected items in your listview using a contextual action bar (CAB). A contextual action bar appears at the top of the screen to present actions the user can perform on the currently selected items. The user can select multiple items, deselect items, and continue to navigate within the listview. We will create a listview to show texts and images and on listview long item click will allow the users to select multiple items and on delete button click will remove the selected items. So lets begin…
Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project MultipleDeleteListView.
Application Name : MultipleDeleteListView
Project Name : MultipleDeleteListView
Package Name : com.androidbegin.multipledeletelistview
Open your MainActivity.java and paste the following code.
MainActivity.java
package com.androidbegin.multipledeletelistview; import android.os.Bundle; import android.app.Activity; import android.widget.ListView; import android.util.SparseBooleanArray; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import java.util.ArrayList; import java.util.List; import android.widget.AbsListView.MultiChoiceModeListener; public class MainActivity extends Activity { // Declare Variables ListView list; ListViewAdapter listviewadapter; List<WorldPopulation> worldpopulationlist = new ArrayList<WorldPopulation>(); String[] rank; String[] country; String[] population; int[] flag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get the view from listview_main.xml setContentView(R.layout.listview_main); // Generate sample data into string arrays rank = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; country = new String[] { "China", "India", "United States", "Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh", "Russia", "Japan" }; population = new String[] { "1,354,040,000", "1,210,193,422", "315,761,000", "237,641,326", "193,946,886", "182,912,000", "170,901,000", "152,518,015", "143,369,806", "127,360,000" }; flag = new int[] { R.drawable.china, R.drawable.india, R.drawable.unitedstates, R.drawable.indonesia, R.drawable.brazil, R.drawable.pakistan, R.drawable.nigeria, R.drawable.bangladesh, R.drawable.russia, R.drawable.japan }; for (int i = 0; i < rank.length; i++) { WorldPopulation worldpopulation = new WorldPopulation(flag[i], rank[i], country[i], population[i]); worldpopulationlist.add(worldpopulation); } // Locate the ListView in listview_main.xml list = (ListView) findViewById(R.id.listview); // Pass results to ListViewAdapter Class listviewadapter = new ListViewAdapter(this, R.layout.listview_item, worldpopulationlist); // Binds the Adapter to the ListView list.setAdapter(listviewadapter); list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); // Capture ListView item click list.setMultiChoiceModeListener(new MultiChoiceModeListener() { @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { // Capture total checked items final int checkedCount = list.getCheckedItemCount(); // Set the CAB title according to total checked items mode.setTitle(checkedCount + " Selected"); // Calls toggleSelection method from ListViewAdapter Class listviewadapter.toggleSelection(position); } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.delete: // Calls getSelectedIds method from ListViewAdapter Class SparseBooleanArray selected = listviewadapter .getSelectedIds(); // Captures all selected ids with a loop for (int i = (selected.size() - 1); i >= 0; i--) { if (selected.valueAt(i)) { WorldPopulation selecteditem = listviewadapter .getItem(selected.keyAt(i)); // Remove selected items following the ids listviewadapter.remove(selecteditem); } } // Close CAB mode.finish(); return true; default: return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public void onDestroyActionMode(ActionMode mode) { // TODO Auto-generated method stub listviewadapter.removeSelection(); } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub return false; } }); } }
In this activity, we have created string arrays with sample data and pass it into the ListViewAdapter class. On listview long item click will allow the user to select multiple items.
We have prepared some sample images for this tutorial. Insert your downloaded sample images into your res > drawable-hdpi.
Sample Images
[wpfilebase tag=file id=35 tpl=download-button /]
Next, create an XML graphical layout for your MainActivity. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file listview_main.xml and paste the following code.
listview_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@+id/listview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout>
Next, create an XML graphical layout for your contextual action bar (CAB). Go to res > menu > Right Click on menu > New > Android XML File
Name your new XML file activity_main.xml and paste the following code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/delete" android:title="@string/delete"/> </menu>
Next, create an array class. Go to File > New > Class and name it WorldPopulation.java. Select your package named com.androidbegin.multipledeletelistview and click Finish.
Open your WorldPopulation.java and paste the following code.
WorldPopulation.java
package com.androidbegin.multipledeletelistview; public class WorldPopulation { private String rank; private String country; private String population; private int flag; public WorldPopulation(int flag, String rank, String country, String population) { this.rank = rank; this.country = country; this.population = population; this.flag = flag; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPopulation() { return population; } public void setPopulation(String population) { this.population = population; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } }
Next, create a custom listview adapter. Go to File > New > Class and name it ListViewAdapter.java. Select your package named com.androidbegin.multipledeletelistview and click Finish.
Open your ListViewAdapter.java and paste the following code.
ListViewAdapter.java
package com.androidbegin.multipledeletelistview; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import android.content.Context; import android.widget.ArrayAdapter; import android.widget.ImageView; public class ListViewAdapter extends ArrayAdapter<WorldPopulation> { // Declare Variables Context context; LayoutInflater inflater; List<WorldPopulation> worldpopulationlist; private SparseBooleanArray mSelectedItemsIds; public ListViewAdapter(Context context, int resourceId, List<WorldPopulation> worldpopulationlist) { super(context, resourceId, worldpopulationlist); mSelectedItemsIds = new SparseBooleanArray(); this.context = context; this.worldpopulationlist = worldpopulationlist; inflater = LayoutInflater.from(context); } private class ViewHolder { TextView rank; TextView country; TextView population; ImageView flag; } 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.rank = (TextView) view.findViewById(R.id.rank); holder.country = (TextView) view.findViewById(R.id.country); holder.population = (TextView) view.findViewById(R.id.population); // Locate the ImageView in listview_item.xml holder.flag = (ImageView) view.findViewById(R.id.flag); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } // Capture position and set to the TextViews holder.rank.setText(worldpopulationlist.get(position).getRank()); holder.country.setText(worldpopulationlist.get(position).getCountry()); holder.population.setText(worldpopulationlist.get(position) .getPopulation()); // Capture position and set to the ImageView holder.flag.setImageResource(worldpopulationlist.get(position) .getFlag()); return view; } @Override public void remove(WorldPopulation object) { worldpopulationlist.remove(object); notifyDataSetChanged(); } public List<WorldPopulation> getWorldPopulation() { return worldpopulationlist; } public void toggleSelection(int position) { selectView(position, !mSelectedItemsIds.get(position)); } public void removeSelection() { mSelectedItemsIds = new SparseBooleanArray(); notifyDataSetChanged(); } public void selectView(int position, boolean value) { if (value) mSelectedItemsIds.put(position, value); else mSelectedItemsIds.delete(position); notifyDataSetChanged(); } public int getSelectedCount() { return mSelectedItemsIds.size(); } public SparseBooleanArray getSelectedIds() { return mSelectedItemsIds; } }
In this custom listview adapter class, string arrays are passed into the ListViewAdapter and set into the TextViews and ImageViews followed by the positions.
Next, create an XML graphical layout for your listview item. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file listview_item.xml and paste the following code.
listview_item.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="?android:attr/activatedBackgroundIndicator" > <TextView android:id="@+id/ranklabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/ranklabel" /> <TextView android:id="@+id/rank" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/ranklabel" /> <TextView android:id="@+id/countrylabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/ranklabel" android:text="@string/countrylabel" /> <TextView android:id="@+id/country" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/rank" android:layout_toRightOf="@+id/countrylabel" /> <TextView android:id="@+id/populationlabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/countrylabel" android:text="@string/populationlabel" /> <TextView android:id="@+id/population" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/country" android:layout_toRightOf="@+id/populationlabel" /> <ImageView android:id="@+id/flag" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:background="#000000" android:padding="1dp" /> </RelativeLayout>
Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code.
strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Multiple Selection ListView</string> <string name="hello_world">Hello world!</string> <string name="ranklabel">"Rank : "</string> <string name="countrylabel">"Country : "</string> <string name="populationlabel">"Population : "</string> <string name="delete">Delete</string> </resources>
In your AndroidManifest.xml, set the minimum SDK version to 11. Refer to this link for more info regarding minimum SDK requirements. Open your AndroidManifest.xml and paste the following code.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidbegin.multipledeletelistview" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Output:
Source Code
[purchase_link id=”8015″ text=”Purchase to Download Source Code” style=”button” color=”green”]
please help i m in much trouble.... here is my project link i also update on stack overflow as u already knowhttps://drive.google.com/file/d/0B1JZK0Gdq2IJWDhlS0dlZ21iVmM/view project link
Adnan Naeem
Android Delete Multiple Selected Items In ListView Tutorial
brother ..?
Adnan Naeem
Android Delete Multiple Selected Items In ListView Tutorial
how to put select all /unselect all feature in it?
MK
Android Delete Multiple Selected Items In ListView Tutorial
how do i fetch that selected item from list view and display them in another screen?
TEJ
Android Delete Multiple Selected Items In ListView Tutorial