2017-08-05 34 views
1

成立了客戶適配器,我會需要能夠從刪除列表視圖。該GetView看起來是這樣的,包括我的觀點持有者以及Xamarin的Android的ListView - 刪除按鈕會多次

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

的問題是雖然,當我點擊刪除按鈕將其與不同的位置,最終得到的地方我有一個觸發點多次碼從列表中刪除項目和位置的值超出範圍,我收到一個異常。

什麼是刪除並從列表視圖中刪除項目的正確方法?

回答

2

替換下面的代碼的代碼,這樣就不會調用許多時間。

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

} 
+0

沒錯該訣竅 –