I have a FragmentActivity with a ViewPager in it - this ViewPager contains three ListViews - each destined to have their own unique adapters (and unique data sets).
I would like to use AsyncTaskLoader to populate these adapters, but ONLY when a given view is selected in the ViewPager.
Is it required to init a loader in the activity's onCreate method? (below code)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foo);
getSupportLoaderManager().initLoader(0, null, this);
getSupportLoaderManager().initLoader(1, null, this);
getSupportLoaderManager().initLoader(2, null, this);
}
Or is it okay to call call initLoader(...) interactively, such as the result of a listener for OnPageChangeListener.onPageSelected ?
mPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int newPage) {
getSupportLoaderManager().initLoader(newPage, null, this);
}
...
}
I want to avoid having to perform potentially 3 time consuming loaders up front if the user may only ever look at the first view in the pager.
EDIT: Or would it be a better design to have the ViewPager use a Fragment for each view, and each fragment would be responsible for managing its own loader?
I don't remember the details, but at least with the compatibility library, if you don't call initLoader()
from onCreate()
, the loader's lifecycle gets messed up, so you might want to call them from onCreate()
(might be fixed in the latest version, haven't tested). IIRC, fragments just use the activity's LoaderManager, so loaders are always managed by the activity. Using fragments will generally make your code cleaner, so do migrate to fragments if possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With