View pager和fragment生命周期
View pager that i created loads three pages at a time. now if i swipe from page 1 to 2 then to 3.when the third page is the current item,the first page(fragment) goes to onPause().now if i swipe to second page,1st page comes to onResume() even though the page 1 is still not visible to the user. So my question is how to distinguish between the first and second page in code?for example if i have to run a piece of code when the fragment is visible, how is that done?
The FragmentPagerAdapter keeps additional fragments, besides the one shown, in resumed state. The solution is to implement a custom OnPageChangeListener and create a new method for when the fragment is shown.
Solution:
- Create LifecycleManager Interface The interface will have two methods and each ViewPager’s Fragment will implement it. These methods Are as follows:
1 | public interface FragmentLifecycle { |
- Let each Fragment implement the interface Add iplements statement for each class declaration:
1 | public class FragmentBlue extends Fragment implements FragmentLifecycle |
- Implement interface methods in each fragment In order to check that it really works as expected, I will just log the method call and show Toast:
1 |
|
- Call interface methods on ViewPager page change You can set OnPageChangeListener on ViewPager and get callback each time when ViewPager shows another page:
1 | pager.setOnPageChangeListener(pageChangeListener); |
Implement OnPageChangeListener to call your custom Lifecycle methods
Listener knows the new position and can call the interface method on new Fragment with the help of PagerAdapter. I can here call onResumeFragment() for new fragment and onPauseFragment() on the current one.
I need to store also the current fragment’s position (initially the current position is equal to 0), since I don’t know whether the user scrolled from left to right or from right to left. See what I mean in code:
private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20int currentPosition = 0;
public void onPageSelected(int newPosition) {
FragmentLifecycle fragmentToShow = (FragmentLifecycle)pageAdapter.getItem(newPosition);
fragmentToShow.onResumeFragment();
FragmentLifecycle fragmentToHide = (FragmentLifecycle)pageAdapter.getItem(currentPosition);
fragmentToHide.onPauseFragment();
currentPosition = newPosition;
}
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
};