我有一个填充的listView购买自定义CursorAdapter。我在每一行上都有一个按钮,单击该按钮可切换数据库中的值并更改图标视图。该按钮的侦听器添加在bindView方法中。问题是,当发生这种情况时,光标不会更新,因此下次重新绘制列表时(键盘弹出并消失,或滚动列表),图标将恢复为原始视图。因为这一切都发生在CursorAdapter类中,所以我无法从那里重新加载游标,并且重新查询被取消。如何在数据更改时触发光标重新加载?我不想在这个简单的任务中使用ContentProvider和ContentObserver。这似乎是基本的,但我一直在倾倒这个网站和许多其他人,敲打我的头在墙上花了几个小时。
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder mvh = (ViewHolder)view.getTag();
TextView productName = mvh.name;
productName.setText(cursor.getString(cursor.getColumnIndex(ProductsDbAdapter.KEY_PRODUCT_NAME)));
ImageView addShoppingIcon = mvh.addShopIcon;
//get icon state from cursor.
boolean isneeded = (cursor.getInt(cursor.getColumnIndex(ProductsDbAdapter.KEY_PRODUCT_ISNEEDED)) == 0 ? false : true);
//set icon tag with icon data for OnClick
long rowid = cursor.getLong(cursor.getColumnIndex(ProductsDbAdapter.KEY_ROWID));
addShoppingIcon.setTag(new PantryHolder(rowid,inpantry,isneeded));
//set icon bitmap
if(isneeded)
addShoppingIcon.setImageBitmap(MainActivity.mPantryNeedIcon);
else
addShoppingIcon.setImageBitmap(MainActivity.mPantryHasIcon);
//add listener
addShoppingIcon.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
PantryHolder mph = (PantryHolder)v.getTag();
ImageView icon = (ImageView)v;
if(mph.inpantry){
if (mph.isneeded)
icon.setImageBitmap(MainActivity.mPantryHasIcon);
else
icon.setImageBitmap(MainActivity.mPantryNeedIcon);
} else {
if (mph.isneeded)
icon.setImageBitmap(RealMealzActivity.mQuickAddIcon);
else
icon.setImageBitmap(RealMealzActivity.mQuickAddGrayIcon);
}
mph.isneeded = !mph.isneeded;
v.setTag(mph);
//update database using database helper
mDbAdapter.updateIsNeeded(mph.rowid, mph.isneeded);
}
});
}