我正在尝试将数据从SQLiteDatabase绑定(bind)到ListView。我目前正在使用SimpleCursorAdapter填写ListView。不幸的是,这似乎不适用于设置CheckBox的checked属性。

我现在就是这样做的。适配器没有将CheckBox的选中状态更改为文本值,而是将其填充到text参数中,因此该值以文本形式显示在CheckBox的右侧。

Java的:

setListAdapter( new SimpleCursorAdapter( this,
      R.layout.mylist,
      data,
      new String[] { Datenbank.DB_STATE, Datenbank.DB_NAME },
      new int[] { R.id.list_checkbox, R.id.list_text }
    ) );

mylist.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>

<CheckBox android:text=""
    android:id="@+id/list_checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    ></CheckBox>

<TextView android:text=""
    android:id="@+id/list_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ></TextView>

</LinearLayout>

编辑:数据库中的字段当然是 bool 型的,我也尝试为已检查的字段分配ID以填充值。

最佳答案

除了创建一个覆盖newView/bindView或getView的自定义适配器之外,我不确定您将如何执行此操作,具体取决于您覆盖的内容(ResourceCursorAdapter是个不错的选择)。

好的,这是一个例子。我没有测试是否可以编译,因为我正在工作,但这绝对可以为您指明正确的方向:

public class MyActivity extends ListActivity {

    MyAdapter mListAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Cursor myCur = null;

        myCur = do_stuff_here_to_obtain_a_cursor_of_query_results();

        mListAdapter = new MyAdapter(MyActivity.this, myCur);
        setListAdapter(mListAdapter);
    }


    private class MyAdapter extends ResourceCursorAdapter {

        public MyAdapter(Context context, Cursor cur) {
            super(context, R.layout.mylist, cur);
        }

        @Override
        public View newView(Context context, Cursor cur, ViewGroup parent) {
            LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return li.inflate(R.layout.mylist, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cur) {
            TextView tvListText = (TextView)view.findViewById(R.id.list_text);
            CheckBox cbListCheck = (CheckBox)view.findViewById(R.id.list_checkbox);

            tvListText.setText(cur.getString(cur.getColumnIndex(Datenbank.DB_NAME)));
            cbListCheck.setChecked((cur.getInt(cur.getColumnIndex(Datenbank.DB_STATE))==0? false:true))));
        }
    }
}

10-07 19:25
查看更多