如何使用下面的代码从列表视图中删除多行,我正在使用MultiChoiceModeListener。
MainActivity
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;
}
EDITED
@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;
}
}
答案 0 :(得分:0)
在onItemCheckedStateChanged
中,您可以跟踪所有已检查的位置或ID(在列表或其他内容中)。
然后当单击某个菜单选项时,您遍历所有位置或ID并从数据集中删除它们。
删除后,请在适配器上调用notifyDatasetChanged