2011-04-06 64 views
3

我有一个列表视图,其中有大约200个项目,我为复选框实现了自定义ArrayAdapter。我使用SparseBooleanArray来存储框的值。Android - ListView:未选中复选框

所有这些工作正常,但我似乎无法图形更新框的检查。如果用户点击,那么该框被检查。但是,如果我在我的代码中调用setChecked,它对框本身没有影响(所以即使它的值为真,也不会打勾)。

我已经通过尝试将所有框设置为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()); 
} 

}

谢谢你们!

+0

可能不值得一提,但即使设置在XML中启用的复选框也没有显示任何内容,当然我错过了一些较小的内容,但是我看不到它! – 2011-04-06 16:58:17

+0

出于好奇,为什么不直接使用ListView中的多重选择支持? http://developer.android.com/reference/android/widget/AbsListView.html#attr_android:choiceMode – 2011-04-06 17:07:48

+0

我已经添加了android:choiceMode是多项选择,但它似乎是普遍的共识是使用自定义适配器。大多数android应用程序似乎都包含复选框。 – 2011-04-06 17:24:39

回答

2

好吧,看来经过文本视图是做的最好的方法,把它们作为列表项,并以此作为你的听众:

  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("[email protected]", address.get(pos) + ": " + subject.get(pos), Jsoup.parse(message.get(pos)).toString()); 
     } 

我以前使用的是由谷歌Android开发人员提供的示例这就是为什么我认为这很平常。但是,不管是不是,这种方式是更简单!