Android ListView reuses rows that have been scrolled out of sight. But this seems to be a problem when handling events in a child view of row in C #.
A valid way to add event handlers in Java is to explicitly set the handler as follows:
ImageView img = (ImageView) row.findViewById(R.id.pic); img.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { System.out.println(position); } });
The documents on the Xamarin website encourage developers to use C # to add an event listener template that does not play good results with reusable strings:
ImageView img = row.FindViewById<ImageView> (Resource.Id.pic); img.Click += (sender, e) => { Console.WriteLine(position); };
The Java template above which the event handler sets is well suited for reusing strings, while the C # template below it, which adds an event handler, causes the handlers to be overloaded on the child Types of repeated strings.
The code below shows my GetView method from a custom BaseAdapter that I wrote.
public override Android.Views.View GetView (int position, View convertView, ViewGroup parent) { View row = convertView; //TODO: solve event listener bug. (reused rows retain events). if (row == null) { row = LayoutInflater.From (userListContext) .Inflate (Resource.Layout.UserListUser, null, false); } ImageView profilePic = row.FindViewById<ImageView> (Resource.Id.profilePic); //if(profilePic.Clickable) { /** kill click handlers? **/ } profilePic.Click += async (object sender, EventArgs e) => { Bundle extras = new Bundle(); extras.PutString("id", UserList[position].id); Intent intent = new Intent(userListContext, typeof(ProfileActivity)); intent.PutExtras(extras); postListContext.StartActivity(intent); }; return row; }
The problem is that when you reuse a string in the profilePic , there is still a handler for the original click.
Is there a way (a) to destroy profilePic.Click or (b) to use the Java profilePic.SetOnClickListener Java template with anonymous functions?
Or, is there a better template to use when the click handler can access the correct position value?