1

我有一个带有 android:choiceMode="multipleChoice" 的 ListView。我通过 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 实际上缺少直截了当的方法。

4

1 回答 1

0

SimpleCursorAdapter.ViewBinder在适配器上使用 a 。确保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;
       }
});
于 2012-11-14T15:43:52.447 回答