安卓 - 列表视图:复选框未保持选中状态

4
我有一个ListView,约有200个项目,我已经为复选框实现了自定义的ArrayAdapter。我使用SparseBooleanArray来存储框的值。
所有这些都很好用,但我似乎无法在图形上更新框的检查状态。如果用户单击,则框将被选中。但是,如果我在我的代码中调用setChecked,则它对框本身没有影响(因此,即使其值为true,它也不会被打勾)。
我尝试将所有框设置为true并没有成功,即使它们都被选中,它们仍然没有显示出来。不确定你需要看到什么代码,但我为了保险起见将我的适配器扔进来了:
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()); 
} 

感谢大家!


可能不值得一提,但即使在XML中将复选框设置为启用也没有显示任何内容,我确定我错过了一些细微的东西,但我看不到它! - Christopher Gwilliams
出于好奇,为什么不直接在ListView中使用内置的多选支持呢?http://developer.android.com/reference/android/widget/AbsListView.html#attr_android:choiceMode - Cheryl Simon
我已将android:choiceMode添加为多选,但普遍的共识似乎是使用自定义适配器。大多数Android应用程序似乎都包含复选框。 - Christopher Gwilliams
普遍共识在哪里?在什么情况下?我认为这些并不是互斥的。关键是你不应该需要自己跟踪已选状态,你应该能够通过http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemIds()直接请求已选项目。 - Cheryl Simon
1个回答

2

好的,看起来 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开发者提供的,所以我认为这是很常见的。但无论它是否常见,这种方法都要简单得多!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接