jeudi 22 septembre 2016

Xamarin Android Listview with Checkbox is checking more than one checkbox

So I've been working on a app with a listview with checkbox's and I've noticed when I select a item say the first item on the list when I scroll down the first item after scrolling down a full page has the checkbox selected as well. I have a feeling this is due to recyled views but I'm curious as to the solution for this. I had tried adding a viewholder but this didn't fix the issue. Just wondering what I'm missing. Code for the getview on the adapter is below:

        public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
        {
            Android.Views.View view = convertView;
            if (view == null)
            {
                view = context.LayoutInflater.Inflate(Resource.Layout.GroupTimeTrackerTemplate, parent, false);
            }
            tblWorkers item = this[position];

            view.FindViewById<TextView>(Resource.Id.UserNameTextView).Text = this[position].nWorkerFirstname + " " + this[position].nWorkerLastname;
            view.FindViewById<TextView>(Resource.Id.StatusTextView).Text = this[position].nStatusShort;
            view.FindViewById<TextView>(Resource.Id.UserRoleTextView).Text = this[position].nTitle;
            CheckBox chkSelect = view.FindViewById<CheckBox>(Resource.Id.ChkSelect);
            chkSelect.Tag = item.nWorkerFirstname + " " + item.nWorkerLastname;

            chkSelect.SetOnCheckedChangeListener(null);
            chkSelect.SetOnCheckedChangeListener(new CheckChangeListener(this.context));
            return view;
        }

        private class CheckChangeListener : Java.Lang.Object, CompoundButton.IOnCheckedChangeListener
        {

            private Activity activity;

            public CheckChangeListener(Activity activity)
            {
                this.activity = activity;
            }

            public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
            {
                if (isChecked)
                {
                    string name = (string)buttonView.Tag;
                    string text = string.Format("{0} Checked.", name);
                    Toast.MakeText(this.activity, text, ToastLength.Short).Show();
                }
            }
        }




1 commentaire: