Buttons 1-7 (one for each row) correctly send numbers 1-7 to the edit component activity/screen (the numbers correspond to the row the button is on, based on the 'position'). However, when I tap on button 8-10, it for some reason sends numbers 1-3 to the edit component activity/screen and when I retry buttons 1-3 again, the numbers sent to the edit component activity are all out of sync.
I don't understand how the buttons for rows 1-7 send the correct numbers but all of a sudden row 8 and above don't.
The custom listview adapter class
public override View GetView(int position, View convertView, ViewGroup parent) { View row = convertView; //Row if (row == null) { row = LayoutInflater.From(mContext).Inflate(Resource.Layout.listview_row, null, false); } //Set component details TextView Category = row.FindViewById<TextView>(Resource.Id.txtViewCategory); Category.Text = allComponents[position].CategoryName; TextView Name = row.FindViewById<TextView>(Resource.Id.txtViewName); Name.Text = allComponents[position].Name; TextView Price = row.FindViewById<TextView>(Resource.Id.txtViewPrice); Price.Text = allComponents[position].Price; ImageButton editComponent = row.FindViewById<ImageButton>(Resource.Id.imgBtnEditComponent); //Take the user to the edit screen for a given component if (!editComponent.HasOnClickListeners) { editComponent.Click += (sender, e) => { // Declare the activityas intent var intent = new Intent(mContext, typeof(Edit_componentActivity)); //Store the row position var rowPostion = (position + 1); //Transfer the component's row to the edit screen intent.PutExtra("edit_component_row_position", rowPostion); //Start the activity of intent mContext.StartActivity(intent); }; } return row; }
The edit component activity
// Create your application here SetContentView(Resource.Layout.edit_component); //Get the component's row position var editComponentRowPosition = Intent.GetIntExtra("edit_component_row_position", 0); Toast.MakeText(this, editComponentRowPosition.ToString(), ToastLength.Long).Show(); //Get the notes text view of the screen TextView editName = FindViewById<TextView>(Resource.Id.txtEditEditComponentName); //Assign the notes text view the component's notes editName.Text = editComponentRowPosition.ToString();
Here are some screenshots.
Answers
The items of the list view are reused so
GetView
will be called every time a new item needs to be displayed. It decides to create a new instance or to reuse an existed one.I guess your screen can display 7 items once and now these 7 items are all new instances so that the position could be correct. However, when you scroll to display more items, list view starts to reuse the former cells then the position is messed up. The position is a parameter outside of your click event I suggest replacing this with a reliable property like:
We could retrieve the correct position in this way.