这是带有复选框的列表的 CursorAdapter 示例。
public class ItemCursorAdapter extends CursorAdapter {
private final LayoutInflater inflater;
private int itemNameIndex;
private int itemCheckIndex;
private DBHelper dbHelper;
public ItemCursorAdapter(Context context, Cursor cursor, boolean autoRequery) {
super(context, cursor, autoRequery);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemNameIndex = cursor.getColumnIndex(DBHelper.ITEM.NAME);
itemCheckIndex = cursor.getColumnIndex(DBHelper.ITEM.CHECK);
dbHelper = DBHelper.getInstance(context);
}
public void bindView(View view, Context context, Cursor cursor) {
String name = cursor.getString(itemNameIndex);
boolean checked = cursor.getInt(itemCheckIndex) > 0;
TextView nameTxt = (TextView) view.findViewById(R.id.item_name);
CheckBox checkChk = (CheckBox) view.findViewById(R.id.item_check);
checkChk.setOnCheckedChangeListener(new onItemCheckChangeListener(name));
nameTxt.setText(name);
checkChk.setChecked(checked);
}
@Override
public View newView(Context context, Cursor c, ViewGroup parent) {
View view = inflater.inflate(R.layout.row_item, null);
return view;
}
private class onItemCheckChangeListener implements OnCheckedChangeListener {
private String itemName;
public onItemCheckChangeListener(String itemName) {
this.itemName = itemName;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
dbHelper.changeItemCheck(itemName, isChecked);
}
}
}
And here example of table inside DBHelper
public static interface ITEM extends BaseColumns {
String TABLE_NAME = "itemTable";
String NAME = "itemName";
String CHECK = "itemCheck";
}
Method to get cursor for list
public Cursor getAllItemCursor() {
return getReadableDatabase().rawQuery("SELECT * FROM " + ITEM.TABLE_NAME, null);
}
and to update checkbox status to db
public void changeItemCheck(String itemName, boolean isChecked) {
ContentValues values = new ContentValues();
values.put(ITEM.CHECK, isChecked);
getWritableDatabase().update(ITEM.TABLE_NAME, values, ITEM.NAME + " =? ", new String[] { itemName });
}