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 –