Xamarin Android ListView - 删除按钮多次触发

时间:2017-08-05 04:25:07

标签: c# android xamarin xamarin.android

为列表视图设置客户适配器,我需要能够从中删除。 GetView看起来像这样,包括我的视图持有者的代码

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; }
    }

问题是,当我点击删除按钮时,它会以不同的位置多次触发,最终到达我已从列表中删除项目并且位置值超出范围的点我得到例外。

从列表视图中删除和删除项目的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

用以下代码替换代码,这样它就不会多次调用。

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

}