如何使用SimpleCursorAdapter将multipleChoice ListView中的CheckBox绑定到布尔值?

时间:2012-11-14 15:34:47

标签: android listview simplecursoradapter multiple-choice

我有一个带有android的ListView:choiceMode =“multipleChoice”。我通过SimpleCursorAdapter从Cursor填充此ListView。有没有办法直接将ListView的CheckedTextView布局的“CheckBox”绑定到游标的布尔值?

如果值为true,我现在循环调用ListView.setItemChecked()的游标:

private void showMyData(long myId) {
    // fill the list
    String[] fromColumns = { "myTextColumn" };
    int[] toViews = { android.R.id.text1 };
    Cursor myCursor = _myData.readData(myId);
    CursorAdapter myAdapter = new SimpleCursorAdapter(this,
        android.R.layout.simple_list_item_multiple_choice,
        myCursor, fromColumns, toViews);
    ListView myListView = (ListView) findViewById(R.id.myListView);
    myListView.setAdapter(myAdapter);
    // mark items that include the object specified by myId
    int myBooleanColumnPosition = myCursor
        .getColumnIndex("myBooleanColumn");
    for (int i = 0; i < myCursor.getCount(); i++) {
        myCursor.moveToPosition(i);
        if (myCursor.getInt(myBooleanColumnPosition ) == 1) {
            myListView.setItemChecked(i, true);
        }
    }
}

这就是工作。但我希望有这样的代码:

String[] fromColumns = { "myTextColumn", "myBooleanColumn" };
int[] toViews = { android.R.id.text1, android.R.id.Xyz };

并且没有循环。我在这里遗漏了什么或是Android吗?

修改 我按照Luksprog的建议尝试了这个:

public boolean setViewValue(View view, Cursor cursor,
        int columnIndex) {
    CheckedTextView ctv = (CheckedTextView) view;
    ctv.setText(cursor.getString(cursor
            .getColumnIndex("myTextColumn")));
    if (cursor.getInt(cursor.getColumnIndex("myBooleanColumn")) == 1) {
        ctv.setChecked(true);
        Log.d("MY_TAG", "CheckBox checked");
    }
    return true;
}

记录检查CheckBox但实际上并未执行此操作。也许这是我身边的一个错误。虽然它比初始循环更复杂,但至少感觉就像是在使用框架,而不是反对它。谢谢Luksprog的答案。

但总结一下:Android实际上缺少直接的方法。

1 个答案:

答案 0 :(得分:0)

在适配器上使用SimpleCursorAdapter.ViewBinder。确保您的Cursor中包含布尔值列,然后:

String[] fromColumns = { "myTextColumn" };
int[] toViews = { android.R.id.text1 };
Cursor myCursor = _myData.readData(myId);
CursorAdapter myAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, myCursor, fromColumns, toViews);
myAdapter.setViewBinder(new ViewBinder() {
       public boolean setViewValue (View view, Cursor cursor, int columnIndex) {
          // set the text of the list row, the view parameter (simple use cursor.getString(columnIndex))
          // set the CheckBox status(the layout used in the adapter is a CheckedTextView)
          return true;
       }
});