I want to create a multiple-choice listview; associate the listview to a contextual menu. The menu has a delete item. When I choose the delete item on the menu, the selected items in the listview must be deleted; of course the listview will appear without the deleted items, but I have problem when selecting delete item. This is my code
String[] mycolors;
ListView myLis;
ArrayAdapter<String> dataAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLis = (ListView) findViewById(R.id.colorList);
mycolors = getResources().getStringArray(R.array.colors_array);
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, mycolors);
myLis.setChoiceMode(2);
myLis.setAdapter(dataAdapter);
myLis.setOnCreateContextMenuListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void CreateMenu(Menu menu) {
MenuItem mnu1 = menu.add(0, 0, 0, "Delete");
MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");
}
private boolean MenuChoice(MenuItem item) {
switch (item.getItemId()) {
case 0:
deleteSelectedItems();
return true;
case 1:
Toast.makeText(this, "You clicked on Item 2", Toast.LENGTH_LONG)
.show();
return true;
}
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu(menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return MenuChoice(item);
}
public void deleteSelectedItems(){
SparseBooleanArray checkedItemPositions = new SparseBooleanArray();
checkedItemPositions.clear();
checkedItemPositions = myLis.getCheckedItemPositions();
int itemCount = checkedItemPositions.size();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
Object toRemove = dataAdapter.getItem(i);
dataAdapter.remove((String)toRemove);
}
}
checkedItemPositions.clear();
dataAdapter.notifyDataSetChanged();
}
}