package com.example.listview_multiples_selection03;

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<Shopping> shoppinglist = new ArrayList<Shopping>();
	String[] Item;
	String[] Price;

	@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
Item = new String[]{ "Bread", "Water", "Milk", "Crackers", "Salt",
"Butter", "Flour", "Cheese", "Apples", "Ham" };
Price = new String[]{"1.00$", "3.50$", "2.50$",
"1.25$", "4.50$", "3.00$", "5.00$", "3.25$",
"2.75$", "7.50$" };
for (int i = 0; i < Item.length; i++) {
Shopping shopping = new Shopping(Item[i], Price[i]);
shoppinglist.add(shopping);
}
// 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,
shoppinglist);

//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)) {
Shopping 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.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;
}
});
}
}