Nestor
Nestor

Reputation: 8384

ExpandableListView child item's CheckBox gets checked randomly

I created an ExpandableListView with a quite complex child item xml. It contains a TextView, a Checkbox and an EditText. Here is the CheckBox part:

 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
               android:layout_width="match_parent"
               android:layout_height="55dip"
               android:orientation="horizontal"
               android:stretchColumns="0">
  <TableRow>
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  >
  <TextView
      android:id="@+id/lblListItem"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="14dip"
      android:paddingTop="2dp"
      android:paddingBottom="2dp"
      android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"/>
  <CheckBox
      android:id="@+id/cboxIsRel"
      android:layout_width="wrap_content"
            android:layout_height="wrap_content">

  </CheckBox>
  </TableRow>
  </TableLayout>

If I check the 1st item, in every group the 5th item is also gets checked (if the 2nd is selected, then the 6th gets selected).

Why do they get also selected?

UPDATE:

In the getChildView method I have this code:

if (convertView == null)
{
  LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  convertView = infalInflater.inflate(R.layout.expandable_list_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
txtListChild.setText(childText);

If I don't use the convertView check, then the checkbox isn't reused but also the selected checkbox gets unselected if I scroll out.

Upvotes: 3

Views: 2263

Answers (1)

Marcio Covre
Marcio Covre

Reputation: 4556

It's because of recycling of the views.

Make sure that on your adapter, the bindView() or getView() methods sets the checkbox as checked or not.

Edit:

ListView reuses the views to improve performance, so In your case the 1st item is checked, then the same view is used on the 5th child, so its why it is also checked.

So to prevent this from happening, you must save which position is checked and on your getChildView() method you should check/uncheck your checkbox based on the saved value.

This way, you check the 1st item, then you scroll and the view is recycled to the 5th child, the adapter will call getChildView for position 5 and you will check if it was checked. Since it's not checked, you call setchecked(false) on the checkbox and it will appear unchecked.

Upvotes: 3

Related Questions