2016-12-26 115 views
3

即時通訊Xamarin開發基本的Android應用程序,其中我有ListView與ListItem設置在適配器。但是當我刪除或編輯任何項目時,listview不會自行刷新。我知道ObservableCollection,但我不知道如何將它與適配器一起使用。有人能幫助我嗎? Im在Xamarin中是新的。Android Xamarin - ListView適配器與ObservableCollection

適配器:

public class MealsAdapter : BaseAdapter<Meal> 
{ 
    List<Meal> items; 
    Activity context; 

    public MealsAdapter(Activity context, List<Meal> items) 
     : base() 
    { 
     this.context = context; 
     this.items = items; 
    } 

    public override Meal this[int position] 
    { 
     get 
     { 
      return items[position]; 
     } 
    } 

    public override int Count 
    { 
     get 
     { 
      return items.Count; 
     } 
    } 

    public override long GetItemId(int position) 
    { 
     return position; 
    } 

    public override View GetView(int position, View convertView, ViewGroup parent) 
    { 
     var item = items[position]; 

     View view = convertView; 
     if (view == null) 
      view = context.LayoutInflater.Inflate(Resource.Layout.MealListItem, null); 
     view.FindViewById<TextView>(Resource.Id.textViewNazev).Text = item.Name; 
     view.FindViewById<TextView>(Resource.Id.textViewBilkoviny).Text = context.Resources.GetString(Resource.String.BilkovinyNadpis) + ": " + item.Bilkoviny.ToString(); 
     view.FindViewById<TextView>(Resource.Id.textViewSacharidy).Text = context.Resources.GetString(Resource.String.SacharidyNadpis) + ": " + item.Sacharidy.ToString(); 

     return view; 
    } 
} 

的ListView:

ListView listView;  
protected override void OnCreate(Bundle savedInstanceState) 
      { 
       base.OnCreate(savedInstanceState); 
       SetContentView(Resource.Layout.MealsSettings); 

       listView = FindViewById<ListView>(Resource.Id.listViewJidlo); 

       listView.Adapter = new MealsAdapter(this, DataStorage.meallist); 
       listView.ItemClick += ListView_ItemClick; 
      } 

DataStorage.meallist是簡單列表。我已經嘗試把ObservableCollection放到適配器和DataStorage.meallist中,但它沒有幫助。

回答

1

您將需要致電NotifyDataSetChanged()ListView知道它的集合已更改。

無論您在刪除/刪除List<Meal> items中的物品,請務必在事後致電NotifyDataSetChanged()