我正在使用此处链接中的源代码
从上面的来源,我尝试选择选中的项目并从列表中删除。
在布局中添加删除按钮:
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete" />
将选择模式设置为 multichoice :
adapter = new MyAdapter(this,getModel());
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
del_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DeleteSelecteditems();
}
});
这是 DeleteSelecteditems 方法:
DeleteSelecteditems(){
int len = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
Log.d("DeleteSelecteditems","no of checked item:"+checked.size());
for (int i = 0; i < checked.size(); i++){
//item position in adapter
int pos= checked.keyAt(i);
Log.d("DeleteSelecteditems","pos: "+pos);
boolean valueat = checked.valueAt(i);
boolean get = checked.get(i);
Log.d("DeleteSelecteditems","get: "+get+" valueat:"+valueat);
if (checked.valueAt(i)) {
Model item = adapter.getItem(pos);//list.get(i);
adapter.remove(item);
adapter.notifyDataSetChanged();
}
}
获取视图()
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.check, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
}
检查的数组总是有 13 个项目,所有的值都是假的。为什么?