1
votes

Set up a customer adapter for a list view that I'll need to be able to delete from. The GetView looks like this, including the code for my view holder as well

public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var row = convertView;
        IngredientHolder holder = null;

        if (row == null)
        {
            row = _context.LayoutInflater.Inflate(Resource.Layout.EditableIngredientListViewItem, null);
            holder = new IngredientHolder
            {
                IngredientName = row.FindViewById<EditText>(Resource.Id.editableIngredientNameTextView),
                Measurement = row.FindViewById<EditText>(Resource.Id.measurement),
                DeleteButton = row.FindViewById<ImageButton>(Resource.Id.delete_ingredient)
            };

            row.Tag = holder;
        }
        else
        {
            holder = row.Tag as IngredientHolder;
        }

        var ingredient = IngredientList[position];
        holder.Measurement.Text = ingredient.Measurement;
        holder.IngredientName.Text = ingredient.Name;
        holder.DeleteButton.Click += (sender, args) =>
        {
            IngredientList.RemoveAt(position);
            NotifyDataSetChanged();
        };

        return row;
    }

    private class IngredientHolder : Java.Lang.Object
    {
        public TextView IngredientName { get; set; }
        public TextView Measurement { get; set; }
        public ImageButton DeleteButton { get; set; }
    }

The problem is though, that when I click a delete button it fires many times with different positions eventually getting to a point where I've removed items from the list and the value of position is out of range and I get an exception.

What is the proper way to delete and remove items from a listview?

1

1 Answers

2
votes

Replace code with below code,so that it will not call many time.

if (! holder.DeleteButton.HasOnClickListeners)
{
 holder.DeleteButton.Click += (sender, args) =>
        {
            IngredientList.RemoveAt(holder.AdapterPosition);
            NotifyDataSetChanged();
        };

}