我正在使用带有 ListView 的 CursorAdapter 和从 sqlite 数据库获取数据的游标。我有一个名为 RenderList() 的函数,每次我使用列表的新项目更新数据库时,或者如果我将一行的选中值设置为 1(这将添加新项目或删除项目名称)时,我都会调用该函数。
private void renderList(){
String showWhere = show_checked ? null : DbHelper.C_CHECKED + "= '0' ";
try {
db = dbHelper.getReadableDatabase();
cursor = db.query(DbHelper.TABLE, null, showWhere, null, null, null, dbHelper.C_ID + " DESC");
groceriesList = (ListView)findViewById(R.id.listView1);
adapter = new GroceryAdapter(this, cursor);
adapter.newView(getApplicationContext(), cursor, groceriesList);
groceriesList.setAdapter(adapter);
groceriesList.setOnItemClickListener(itemListener);
} catch (Exception e) {
Log.d(TAG, "RenderList Error: ",e);
}
}
这将重置列表,因此如果我单击列表视图下方的项目,它将列表视图重置到顶部位置。显然,我缺少如何以有效且可用的方式更新列表视图和数据库的内容?
public class GroceryAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
public GroceryAdapter(Context context, Cursor cursor) {
super(context, cursor, true);
mInflater = LayoutInflater.from(context);
// mContext = context;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TwoLineListItem listItem = (TwoLineListItem)view;
TextView t1 = listItem.getText1();
TextView t2 = listItem.getText2();
t1.setText(cursor.getString(cursor.getColumnIndex(DbHelper.C_GROCERY)));
t2.setText("Added by: Wes");
t1.setTag(cursor.getInt(cursor.getColumnIndex(DbHelper.C_ID)));
t2.setTag(cursor.getInt(cursor.getColumnIndex(DbHelper.C_CHECKED)));
if (cursor.getInt(cursor.getColumnIndex(DbHelper.C_CHECKED)) == 1 ) {
t1.setPaintFlags(t1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
listItem.setBackgroundColor(0xEECCCCCC);
} else {
t1.setPaintFlags(t1.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG) );
listItem.setBackgroundColor(0x00000000);
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.grocery_list_item, parent, false);
return view;
}
}