Here is how I have implemented bindView:
@Override
public void bindView(View view, Context context, Cursor cursor)
{
final ViewHolder holder = (ViewHolder) view.getTag();
String name = (cursor.getString(cursor.getColumnIndexOrThrow("NotificationDateFor")));
String image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));
System.out.println("cursor.getPosition(test): "+cursor.getPosition());
holder.nametext.setText(name);
// setImage(image, holder.iv);
holder.chk.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v)
{
if (holder.chk.isChecked())
{
itemChecked.set(cursor.getPosition(), true);
System.out.println("cursor.getPosition(true): "+cursor.getPosition());
}
else if (!holder.chk.isChecked())
{
itemChecked.set(cursor.getPosition(), false);
System.out.println("cursor.getPosition(false): "+cursor.getPosition());
// AddDelete
}
}
});
holder.chk.setChecked(itemChecked.get(cursor.getPosition()));
}
The problem occurs at itemChecked.set(cursor.getPosition(), true);
The description of the problem suggests me:
Cannot refer to a non-final variable cursor inside an inner class defined in a different method, change the modifier of Cursor to final.
However if I do final Cursor cursor
, the position value inside the onClick does not get refreshed on scroll. I always get value of 5 if I do a System.out.println("cursor.getPosition(true): "+cursor.getPosition());
and my checkbox check gets messed up again.
As error says... Inside the listener you cannot modify some variables, due it's inner class, so declare variables final:
public void bindView(View view, Context context, final Cursor cursor) {
If you need to modify cursor, use the values needed as final:
final int position = cursor.getPosition();
@Override
public void bindView(View view, Context context, Cursor cursor) {
final ViewHolder holder = (ViewHolder) view.getTag();
final int position = cursor.getPosition();
String name = (cursor.getString(cursor.getColumnIndexOrThrow("NotificationDateFor")));
String image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));
System.out.println("cursor.getPosition(test): "+position);
holder.nametext.setText(name);
// setImage(image, holder.iv);
holder.chk.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (holder.chk.isChecked()) {
itemChecked.set(position, true);
System.out.println("cursor.getPosition(true): "+position);
} else if (!holder.chk.isChecked()) {
itemChecked.set(position, false);
System.out.println("cursor.getPosition(false): "+position);
// AddDelete
}
}
});
holder.chk.setChecked(itemChecked.get(position));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.