Reputation: 1437
I'm trying to figure out if there is a way of controlling when the lifecycle of a Fragment is processed when combined with a FragmentPagerAdapter.
My goal is to trigger an AsyncTask of the currently visible Fragment, when the user swipes it into view.
As of now, I have only been able to create an application that, when the FragmentPagerAdapter code is run, instantiates all the Fragments I'd like to have available completing the "full launching lifecycle" of every Fragment, at once.
I'd like the Fragment's AsyncTask to get triggered when the Fragment comes into view, cancelling it when it goes out of view. I have tried to override all available callbacks on every Fragment, but I have yet to find a callback or listener that reacts when a specific Fragment is shown/not shown.
I'm using the Android Support package v4 with a ViewPager as my base for the application.
Upvotes: 4
Views: 2122
Reputation: 3876
You're probably looking for the .setOnPageChangedListener()
-method. Either call mViewPager.setOnPageChangedListener(new OnPageChangedListener() { ... })
or implement ViewPager.OnPageChangedListener
in your adapter (and set mViewPager.setOnPageChangedListener(mAdapter)
).
In the onPageSelected()
-method, execute your asynctask and cancel any previous instances. This way your asynctask will be executed when your page is (completely) visible. If you want to execute it as soon as the user starts scrolling, manipulate the onPageScrollStatechanged()
and onPageScrolled()
-methods instead.
Example:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// TODO Auto-generated method stub
}
@Override
public void onPageSelected(int position) {
// check if asyncTask exists and is running; if so, cancel it.
if(mAsyncTask != null) {
if(mAsyncTask.getStatus() != AsyncTask.Status.FINISHED) {
mAsyncTask.cancel(true); // cancel asynctask if activity is destroyed before it's finished
}
mAsyncTask = null;
}
mAsyncTask = new MyAsyncTask().execute("myParam");
}
});
Upvotes: 3