[英]Android - ListView: Checkboxes not staying checked
我有一个列表视图,大约有200个项目,我为复选框实现了一个自定义ArrayAdapter。 我使用SparseBooleanArray来存储盒子的值。
所有这些都工作正常,但我似乎无法以图形方式更新复选框的检查。 如果用户单击,则选中该框。 但是,如果我在代码中调用setChecked,则它对框本身没有影响(因此,即使其值为true,也不会对其进行打勾)。
我通过尝试将所有框都设置为true并没有运气进行了测试,即使它们都已选中,也并不表明它们是正确的。 不知道您需要查看什么代码,但是为了更好的实现,我已经插入了Adapter:
class CheckBoxArrayAdapter extends ArrayAdapter<String> implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray checkedBoxes;
Context context;
public CheckBoxArrayAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
checkedBoxes = new SparseBooleanArray();
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final CheckBox view = (CheckBox) super.getView(position, convertView, parent);
//if(convertView == null) {
//convertView = view.inflate(context, R.layout.list_item, null);
//}
view.setTag(position);
view.setChecked(checkedBoxes.get(position, false));
System.out.println(view.getTag() + ": " + view.isChecked());
view.setOnCheckedChangeListener(this);
return view;
}
public boolean isChecked(int position) {
return checkedBoxes.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
checkedBoxes.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkedBoxes.put((Integer) buttonView.getTag(), buttonView.isChecked());
}
}
多谢你们!
好的,似乎Checked Text View是最好的方法,将它们用作列表项,并将其用作您的侦听器:
public void onItemClick(AdapterView<?> parent, View view, int pos,long id)
{
if(!isChecked.get(pos)) {
messageList.setItemChecked(pos, true);
isChecked.put(pos, true);
}else{
messageList.setItemChecked(pos, false);
isChecked.put(pos, false);
}
//sendEmail("encima+Gmail4wrdr@gmail.com", address.get(pos) + ": " + subject.get(pos), Jsoup.parse(message.get(pos)).toString());
}
我之前使用的示例是由Google Android开发人员提供的,这就是为什么我认为它很普通。 但是,无论是与否,这样就简单多了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.