0

我有一个片段,只有一个列表视图。我正在从我的数据库中加载收藏夹,如下所示。如何异步加载它们?目前我被迫在加载视图时使异步方法同步。我希望它可以加载视图,然后在结果准备好时填充它们以使其更快。它不仅仅是微优化,我想学习如何正确地做到这一点。

  public class FavoriteFragment : Fragment
  {
    public event EventHandler<Favorite> FavoriteSelected;

    private FavoriteAdapter _lstAdapter;
    private List<Favorite> _favorites;
    private Repository _repo;

    public override void OnCreate(Bundle savedInstanceState) {
      base.OnCreate(savedInstanceState);
      _repo = TinyIoCContainer.Current.Resolve<Repository>();
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      var view = inflater.Inflate(Resource.Layout.fragment_favorite, container, false);

      var lstFavorites = view.FindViewById<ListView>(Resource.Id.lstFavorites);
      _favorites = Task.Run(async () => await _repo.GetFavoritesAsync()).Result;
      _lstAdapter = new FavoriteAdapter(Activity, _favorites);
      lstFavorites.Adapter = _lstAdapter;
      lstFavorites.ItemClick += (s, e) => FavoriteSelected?.Invoke(this, _favorites[e.Position]);

      return view;
    }
4

1 回答 1

0

从这个线程onActivityCreated(),您可以使用 OnActivityCreated() 加载数据。

 public override async void OnActivityCreated(Bundle savedInstanceState)
{
    base.OnActivityCreated(savedInstanceState);


    await LoadData();
}
private async Task LoadData()
{
 //get data 
}
于 2020-11-16T07:00:53.803 回答