我正在使用带有可点击项目的自定义适配器。问题是,当我滚动列表视图时,它会重新运行项目点击中存在的代码。 如何禁用listview执行此操作?
以下是我的适配器示例:
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.InventoryPreview, null, false);
}
TextView txtInventoryName = row.FindViewById<TextView>(Resource.Id.txtInventoryName);
Button ExtraBtn = row.FindViewById<Button>(Resource.Id.ExtrasBtn);
txtInventoryName.Click += (sender, e) =>
{
var db = new SQLiteConnection(Connection.dpPath);
db.CreateTable<OrderPreviewClass>();
OrderPreviewClass tbl = new OrderPreviewClass();
Connection.InventoryItemID = mitems[position].InventoryItemID;
Connection.InventoryItemName = mitems[position].InventoryItemName;
Connection.RetailPrice = mitems[position].InventoryItemPrice;
Connection.Quantity = "1";
tbl.CategoryID = Connection.CategoryID;
tbl.InventoryItemID = Connection.InventoryItemID;
tbl.Description = Connection.InventoryItemName;
tbl.Quantity = Connection.Quantity;
tbl.Price = Connection.RetailPrice;
tbl.ExtrasPrice = "0";
tbl.RealPrice = Connection.RetailPrice;
tbl.Extras = ",";
db.Insert(tbl);
Toast toast = Toast.MakeText(mContext, "x1 " + txtInventoryName.Text, ToastLength.Short);
toast.Show();
};
ExtraBtn.Click += (sender, e) =>
{
Connection.InventoryItemID = mitems[position].InventoryItemID;
Connection.InventoryItemName = mitems[position].InventoryItemName;
Connection.RetailPrice = mitems[position].InventoryItemPrice;
Toast toast = Toast.MakeText(mContext, txtInventoryName.Text, ToastLength.Short);
toast.Show();
mContext.StartActivity(typeof(ExtrasPreviewMain));
};
return row;
}
每次listview滚动时,如何停止重新运行代码?我应该使用ClickListener吗?
答案 0 :(得分:0)
原因是您的单元格被回收,因此每次单元格被回收时,您都会向文本控件和按钮添加另一个事件 - C#中的事件是多播委托,因此可以触发多个事物。
每次回收单元格时,都会添加另一个事件处理程序。
简单修复是将两个处理程序都提取到方法或本地函数而不是lambdas中,并且在添加之前总是删除处理程序。
类似的东西:
void TextHandler(object sender, EventArgs args) =
{
var db = new SQLiteConnection(Connection.dpPath);
... // rest of the handler here
}
// remove the handler - doesn't matter if it's not already set
txtInventoryName.Click -= TextHandler;
// set the handler
txtInventoryName.Click += TextHandler;