Hi
I have a switch as part of the Customcontroller for my list view
I added delegate to it inside the controller but it runs the code on each item on load of the listview
my getView code is
public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; if (myEvents[position]!=null) { if (view == null) { view = context.LayoutInflater.Inflate(Resource.Layout.EventListItem, null); view.FindViewById<TextView>(Resource.Id.eventTitle).Text = myEvents[position].EventName.ToString(); view.FindViewById<Switch>(Resource.Id.switch4).Checked = myEvents[position].AlarmSet; if (myEvents[position].EventDescription != null) { view.FindViewById<TextView>(Resource.Id.EventDescription).Text = myEvents[position].EventDescription.ToString(); } view.FindViewById<TextView>(Resource.Id.eventStartDate).Text = myEvents[position].TimeLogged.ToString(); view.FindViewById < TextView>(Resource.Id.eventId).Text = myEvents[position].id.ToString(); if (MyUtils.IsOdd(position)) { view.SetBackgroundColor(Android.Graphics.Color.Azure); } else { view.SetBackgroundColor(Android.Graphics.Color.BurlyWood); } } } Switch ASwitch = view.FindViewById<Switch>(Resource.Id.switch4); ASwitch.Click += delegate { MyUtils.ChangeAlarm(myEvents[position].id); }; return view; }
What do i have wrong here??
Regards
M.R.
GetView
will be called over and over again when a view cell needs to be displayed on the screen so the Click
event will be registered multiple times.
We need to put it in the:
if (view == null) { }
This will only be called at the initial time. Try to modify your code like:
public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = LayoutInflater.From(context).Inflate(Resource.Layout.layout_item, parent, false); Switch switchBtn = view.FindViewById<Switch>(Resource.Id.switch4); switchBtn.Click += (sender, e) => { var index = (int)((Switch)sender).Tag; Log.WriteLine(LogPriority.Debug, "test", index.ToString()); }; } Switch ASwitch = view.FindViewById<Switch>(Resource.Id.switch4); ASwitch.Checked = myEvents[position].AlarmSet; ASwitch.Tag = position; // ... return view; }
Try to only put the initializing code in the block and if you want to assign the controls' property, it's better to use it like above.
Answers
GetView
will be called over and over again when a view cell needs to be displayed on the screen so theClick
event will be registered multiple times.We need to put it in the:
This will only be called at the initial time. Try to modify your code like:
Try to only put the initializing code in the block and if you want to assign the controls' property, it's better to use it like above.
@LandLu Thanks