Search code examples
androidlistviewcheckboxxamarin.androidlistview-adapter

ListView adapter with many checkboxes


I'm having some minor problems with my listview. Every item has some information and a checkbox. This shows up fine, I can select and deselect checkboxes etc etc.

However I discovered some strange behaviour. Lets say I click the first checkbox at the first row. If the ListView is small so you don't need to scroll down this works fine. But if the ListView is large so I need to scroll down to see all the items, some random item at the bottom also becomes clicked. Same behaviour the other way around, if I click a checkbox at the bottom of the listview and scroll up, some random checkbox is also clicked at top. If i click several checkboxes somewhere, some other place there are the same amount of clicked checkboxes. I figured this happens when GetView(...) is called, meaning when it updates. It then makes some new checkboxes clicked but I don't know why.

Appreciate some help here! :)

SSSCE of my adapter:

public class ListViewAdapterSSCCE : BaseAdapter
{
    private Activity myActivity;
    private string[] someData;
    private int numberOfElements;
    private CheckBox[] boxes;

    public ListViewAdapterSSCCE(Activity activity)
    {
        this.myActivity = activity;

        for (int i = 0; i < numberOfElements; i++)
            this.boxes[i] = new CheckBox(myActivity);
    }

    public void SetData(string[] someData)
    {
        this.someData = someData;
        this.numberOfElements = someData.Length;
    }

    public void CheckAllBoxes(bool isChecked)
    {
        for (int i = 0; i < numberOfElements; i++)
            this.boxes[i].Checked = isChecked;
    }

    public override Java.Lang.Object GetItem(int position)
    {
        return null;
    }

    public override long GetItemId(int position)
    {
        return 10;
    }

    public override int Count
    {
        get { return numberOfElements; }
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        if (convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater)myActivity.GetSystemService(Context.LayoutInflaterService);
            convertView = inflater.Inflate(Resource.Layout.ChildrenList_item, null);
        }

        var itemBox = convertView.FindViewById<CheckBox>(Resource.Id.checkbox);
        this.boxes[position] = itemBox;

        var textView = convertView.FindViewById<TextView>(Resource.Id.item_data);
        textView.Text = this.someData[position];

        return convertView;
    }
}

Solution

  • You can see sample code in here to have an alternative fix for the checkbox state:

    custom checkbox difficulty in android

    If this post helps you, please mark this post as an answer.

    Thanks.