Reputation: 137
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;
}
}
Upvotes: 1
Views: 361
Reputation: 16082
Views in list are recycled. Your data list may has 100 rows, but ListView
has only 10 (these visible) rows. When you scroll, rows are recycled. The last row in ListView
goes 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
final List<Boolean> isCheckedList;
initialize it in constructor:
isCheckedList = new ArrayList<Boolean>();
for(int i=0;i<myDataLength;i++){
isCheckedList.add(Boolean.FALSE);
}
and modify getView:
holder.ck.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
isCheckedList.set(position, holder.ck.isChecked());
}
});
in place where you fill rows:
holder.ck.setChecked(isCheckedList.get(position));
To change state of all checkboxes use:
Collections.fill(isCheckedList, Boolean.FALSE);
notifyDataSetChanged();
Upvotes: 2
Reputation: 72331
You need to move this code:
if (flag)
holder.ck.setChecked(true);
else
holder.ck.setChecked(false);
out of your if{}
block.
Upvotes: 1