Pattern for using dynamic loaders to load ListView

2019-06-07 13:45发布

问题:

If I have a ViewPager with a certain number of pages, what would be the best way of loading the data for each page using the Loader framework? Each page contains a ListView with its own adapter instance.

  1. Use a separate loader for each page; or
  2. Use a single loader that checks which pages are not loaded and loads them

The thing is, it's possible the user may want to quickly swipe through a bunch of pages and thus it should be easy to "cancel" loading pages that aren't needed for performance reasons.

On the other hand it seems like there might be an overhead with having a lot of loaders.

EDIT: My Loaders actually need to have dynamic IDs to represent the content they are loading. I'm probably going to go with using a mask on the loader ID, and then once the loader is done call destroyLoader().

回答1:

I would use a separate Loader for each ListFragment. Things will get messy very quickly if you try to manage the fragments' Loaders from the parent Activity (especially if those fragments are being held by a ViewPager). Fragments are supposed to be designed for reuse and should not rely on a specific Activity in order to function properly. The fact that each Activity and each Fragment get their own LoaderManager instance is further evidence that the Android team didn't want developers to have their Activitys loading data for its attached Fragments.

I don't think there will be as much overhead as you are probably expecting there to be... Loaders should retain their data across the component's lifecycle and re-query only when the underlying content has changed. It might be a good idea to use a FragmentStatePagerAdapter too.