user1617102
user1617102

Reputation: 61

CheckBox in ListView deactivated when scrolling

I have a ListView where each ListItem has a CheckBox in it's layout. When a CheckBox is activated and scrolls out of the visible area, it's getting deactivated. I understand ListView reuses the Views and that i have to save the state of the CheckBoxes in my getView() method, but i have two problems there.

Upvotes: 0

Views: 190

Answers (1)

D Yao.
D Yao.

Reputation: 401

You are trying to call setSelected on a String. You need to call it on the checkbox. the variable "list" is an ArrayList of Strings.

In both cases, you are trying to call Checkbox methods on String types. You need to call them on your checkboxes.

**EDIT

What you need to do in getView is the following:

  1. if the convertView is not null, save the state of it to your "viewholder" class by calling the appropriate methods on the children of convertView. You are trying to do this if the convertView IS null, which is wrong.
  2. If the convertView is null, then it isn't a recycled view, and there is nothing to save.

basically, your code should look like this:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;
    if (convertView == null) {
        LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflator.inflate(R.layout.listitem, parent, false);
    } else {
        //you should change viewHolder to simply store a boolean, rather than the entire checkbox. It should just store whether or not the checkbox was checked.
        viewHolder = new ViewHolder();
        viewHolder.text = (TextView) convertView.findViewById(R.id.listcontent);
        viewHolder.isChecked = ((CheckBox) convertView.findViewById(R.id.cb)).isChecked();
        //do whatever else here
    }
    return convertView;
}

Upvotes: 1

Related Questions