1
我有一个列表视图并附加一个自定义CursorAdapter
它。列表视图中的每个项目都有一个图像,我想在发生onClick
时更改此图像。 例如,当我用位置4单击图像时,位置10的图像发生了变化,而图像4未发生变化。等等。 为什么会发生这种情况?SetImageResource()在CursorAdapter的列表视图中不正确地工作
我定制CursorAdapter
是:
public class CustomFehrestAdapter extends CursorAdapter {
String Tag;
ImageView favic;
SQLiteDatabase db;
int pos;
Activity ac;
public CustomFehrestAdapter(Context context, Cursor c,Activity ac,SQLiteDatabase db) {
super(context, c);
this.ac =ac;
this.db = db;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.customfehrestitem,parent,false);
}
@Override
public void bindView(View view, final Context context, final Cursor cursor) {
TextView item = (TextView) view.findViewById(R.id.fehresttxt);
favic = (ImageView) view.findViewById(R.id.favic);
pos = cursor.getPosition();
String title;
title = cursor.getString(cursor.getColumnIndex("titr1"));
final boolean isfav = checkFav(cursor);
if(isfav)favic.setImageResource(R.drawable.fav_ic);
else favic.setImageResource(R.drawable.favnot_ic);
item.setText(title);
final int idx = cursor.getInt(cursor.getColumnIndex("_id"));
// here is my image onClick handler.
favic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!isfav){
db.execSQL("update content set favorite=1 where ID="+idx+";");
System.out.print("Add to favs");
fav.setImageResource(R.drawable.fav_ic);
}
else{
db.execSQL("update content set favorite=0 where ID=" + idx + ";");
System.out.print("Remove from favs");
fav.setImageResource(R.drawable.favnot_ic);
}
}
});
}
public boolean checkFav(Cursor cursor) {
int ppp = (int) favic.getTag();
cursor.moveToFirst();
cursor.moveToPosition(ppp);
int check = cursor.getInt(cursor.getColumnIndex("favorite"));
return check != 0;
}
}
你的答案是正确的。但是需要为更新数据库点击了的项目的ID以及变更图像。我如何访问它? –
favic.setOnClickListener在newView()方法中使用时不工作,我不知道为什么? –
尝试使用viewHolder设计模式...检查了这为你的参考.... http://stackoverflow.com/questions/4567969/viewholder-pattern-correctly-implemented-in-custom-cursoradapter –