Android:CursorAdapter,ListView和CheckBox

Nic*_*ick 16 checkbox android listview

我有自己的布局ListView和CustomCursorAdapter.每行都有自己的复选框.所以...绝对清楚的是,在滚动期间,复选框会松开它们的状态.我发现的唯一的东西是ListView中的Android保存复选框状态与光标适配器,但没有答案.还有一个问题.我的CustorArrayAdapter遇到了同样的问题.我使用SparseBooleanArray解决了这个问题,以保持复选框状态.它工作正常,但每个滚动调用onCheckedChanged.那是正常的吗?这笔交易是我的列表视图描述报警元素和启动(onCheckedChanged的)定期调用/停止报警.许多无意义的行为.

Vik*_*dar 65

我与我相似的问题,ListViewCheckBox和我做了什么来摆脱这个问题的:

  • 创建Boolean Object的ArrayList以存储每个CheckBox的状态
  • 将ArrayList项初始化为默认值false,表示尚未检查CheckBox.
  • 当您单击CheckBox时.针对Checked/Unchecked状态设置检查并将该值存储在ArrayList中.
  • 现在使用setChecked()方法将该位置设置为CheckBox.

请参阅以下代码段:

public class MyDataAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();

// itemChecked will store the position of the checked items.

public MyDataAdapter(Context context, int layout, Cursor c, String[] from,
        int[] to) {
    super(context, layout, c, from, to);
    this.c = c;
    this.context = context;

    for (int i = 0; i < this.getCount(); i++) {
        itemChecked.add(i, false); // initializes all items value with false
    }
}

public View getView(final int pos, View inView, ViewGroup parent) {
    if (inView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inView = inflater.inflate(R.layout.your_layout_file, null);
    }

    final CheckBox cBox = (CheckBox) inView.findViewById(R.id.bcheck); // your
    // CheckBox
    cBox.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            CheckBox cb = (CheckBox) v.findViewById(R.id.your_checkbox_id);

            if (cb.isChecked()) {
                itemChecked.set(pos, true);
                // do some operations here
            } else if (!cb.isChecked()) {
                itemChecked.set(pos, false);
                // do some operations here
            }
        }
    });
    cBox.setChecked(itemChecked.get(pos)); // this will Check or Uncheck the
    // CheckBox in ListView
    // according to their original
    // position and CheckBox never
    // loss his State when you
    // Scroll the List Items.
    return inView;
}}
Run Code Online (Sandbox Code Playgroud)

  • 我现在就试试......唯一的问题是我有bindView和newView,但我认为它是一样的 (2认同)

dbm*_*dbm 4

当 ListView 中包含可检查项目时,存在一些问题。我建议使用以下链接:

http://tokudu.com/2010/android-checkable-线性-layout/

我认为这很接近你想要的。