I have a strange problem with my checkbox. In my adapter I have a TextView, an ImageView and a CheckBox. I had implement a button for select all/deselect all and everything works fine. The problem is that when I select one checkbox, if I scroll the list there are and other checkbox selected(the distance between them is 10) and I don’t understand why. Can anyone help me?
Here is my adapter :
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private String[] nume;
private LayoutInflater inflater = null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, String[] d, String[] f) {
activity = a;
data = d;
nume = f;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),"Folder2");
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder {
public TextView text;
public ImageView image;
public CheckBox ck;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.image = (ImageView) vi.findViewById(R.id.image);
holder.ck = (CheckBox) vi.findViewById(R.id.chkbox);
if (flag)
holder.ck.setChecked(true);
else
holder.ck.setChecked(false);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.text.setText(nume[position]);
holder.image.setTag(data[position]);
imageLoader.DisplayImage(data[position], activity, holder.image);
return vi;
}
}
Views in list are recycled. Your data list may has 100 rows, but
ListViewhas only 10 (these visible) rows. When you scroll, rows are recycled. The last row inListViewgoes to the first position or the other way. You have to change the state of these rows.You need to keep checkbox state in array, not in views.
Add
initialize it in constructor:
and modify getView:
in place where you fill rows:
To change state of all checkboxes use: