为列表视图设置客户适配器,我需要能够从中删除。 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; }
}
问题是,当我点击删除按钮时,它会以不同的位置多次触发,最终到达我已从列表中删除项目并且位置值超出范围的点我得到例外。
从列表视图中删除和删除项目的正确方法是什么?
答案 0 :(得分:2)
用以下代码替换代码,这样它就不会多次调用。
if (! holder.DeleteButton.HasOnClickListeners)
{
holder.DeleteButton.Click += (sender, args) =>
{
IngredientList.RemoveAt(holder.AdapterPosition);
NotifyDataSetChanged();
};
}