androidlistviewcheckboxlistviewitemcheckedtextview

CheckedTextView with ListView


I have a listview which items are CheckedTextViews with checkboxes. However, whenever I check one and scroll the listview and they hide, when I return back to them by rescrolling up they are not checked anymore! I read on internet that listviews, when are scrolled, somehow the hidden items are recycled (returned to their default state if I'm correct) after you scroll back at them. I also read that in the custom adapter, I have to use a method called "setOnCheckedChangeListener", but checkedTextViews do not have that particular method!! So I think my problem might be with listviews. How can I solve this? Thank you.

UPDATE: So this is my custom adapter and model class.

public CustomAdapter(Context c, Model[] resource) {
    super(c, R.layout.list_item, resource);

    this.context = c;
    this.modelItems = resource;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    convertView = inflater.inflate(R.layout.list_item, parent, false);
    cb = (CheckedTextView) convertView.findViewById(R.id.checkBox1);
    pN = (TextView) convertView.findViewById(R.id.numberId);
    pN.setText(modelItems[position].getPhoneNumber());
    cb.setText(modelItems[position].getName());

    return convertView;
}

This is the model class:

  public Model(String name, String phoneNumber, int value) {
    this.name = name;
    this.value = value;
    this.phoneNumber = phoneNumber;
}

public String getName() {
    return this.name;
}

public int getValue() {
    return this.value;
}

public String getPhoneNumber() {
    return this.phoneNumber;
}

Solution

  • You can save the checkBox's state in your adapter using the onCheckedChanged listener. Then when you are creating your viewHolders, set the checked state of the checkbox using the data from your adapter. Hope it helps!