lundi 2 février 2015

Strange behaviour of checkBox in the listView

I have fragment with a listView, the listview layout contains (TextView, checkBox and ImageView as follows



t1........CB.......IV
t2........CB.......IV
t3........CB.......IV
t4........CB.......IV
t5........CB.......IV
t6........CB.......IV
SaveButton


in the getView() method, I check if the checkbox is checked or not, and if it is checked, I add the checked items to a list.


the problem is when, initially I set all the checkboxes to be unchecked, but when i check the first item, surprisingly, the third item from below is automatically checked, and if i check the 2nd item from above, the 2nd item from below is checked, and if i check the 3rd item from above , then the last item is checked automatically?!!


please have a look at getView() method and let me know what I missed:


getView():



@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

if (convertView == null) {
LayoutInflater layoutinflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutinflater.inflate(R.layout.list_items_layout, null);
}

if (this.checkedItemsList == null) {
this.checkedItemsList = new ArrayList<String>();
}

final TextView tv = (TextView) convertView.findViewById(R.id.tvlist_topic);
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.cbList_hook);
final ImageView iv = (ImageView) convertView.findViewById(R.id.ivList_delete);

tv.setText(this.topicsList.get(position));

cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
checkedItemsList.add(topicsList.get(position));
setCheckedItemsList(checkedItemsList);
Log.d(TAG, "size: " + checkedItemsList.size());
}
}
});

iv.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (cb.isChecked())
cb.setChecked(false);

topicsList.remove(position);
notifyDataSetChanged();
}
});

return convertView;
}




Aucun commentaire:

Enregistrer un commentaire