以下のコードを使用してリストビューから複数の行を削除するにはどうすればよいですか。私は MultiChoiceModeListener を使用しています。
主な活動
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
list.setMultiChoiceModeListener(new MultiChoiceModeListener() {
@Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
// Here you can do something when items are selected/de-selected
final int checkedCount = list.getCheckedItemCount();
// Update the title in the CAB
mode.setTitle(checkedCount + " Selected");
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_clear:
deleteSelectedItems(item.getItemId());
mode.finish();
return true;
default:
return false;
}
}
public void deleteSelectedItems(int id) {
adapter.remove(adapter.getItem(id)); //The method remove(Object) is undefined for the type ListViewAdapter
}
ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
String[] rank;
String[] country;
String[] population;
LayoutInflater inflater;
View itemView;
public ListViewAdapter(Context context, String[] rank, String[] country,
String[] population) {
this.context = context;
this.rank = rank;
this.country = country;
this.population = population;
}
@Override
public int getCount() {
return rank.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.listview_item, parent, false);
txtrank = (TextView) itemView.findViewById(R.id.rank);
txtcountry = (TextView) itemView.findViewById(R.id.country);
txtpopulation = (TextView) itemView.findViewById(R.id.population);
txtrank.setText(rank[position]);
txtcountry.setText(country[position]);
txtpopulation.setText(population[position]);
return itemView;
}
編集済み
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_clear:
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
adapter.remove(adapter.getItem(i));
}
adapter.notifyDataSetChanged();//The method remove(Object) is undefined for the type ListViewAdapter
mode.finish();
return true;
default:
return false;
}
}