Monday, 20 October 2014



Make ViewPager call Fragement’s Lifecycle methods
Hi Again              

Description:

The ViewPager component which was introduced in support library has lot of issues. The Fragments which are used on the ViewPager does not call its lifecycle methods like onResume, onPause, by which it is impossible for updating the fragments.


Root Cause:

If you check the source code of ViewPager, the view pager only have the swiping algorithm. The PagerAdapter which is an abstract class is implemented by the FragmentPagerAdapter. This adapter is like the controller. So the issue is not with these two, the actual issue is with the container which holds the entire fragment. The container which the ViewPager uses is none other than FragmentManager. FragmentManager uses a transaction manager like sqlite to maintain the addition or deletion and that is the FragmentTransaction. Whenever a Viewpager is set with the PageAdapter which contains the fragment, it adds all the Fragments to the container (FragmentManager) using the FragmentTransaction. Therefore it calls the onCreateView,onResume and onPause of all the fragment in one go. This is done for lazy-loading of the fragments to get the smoothness while swiping the fragments.


Overcome this issue:

Google guys have to come with a container for view pager rather than using the FragmentManager and FragmentTransaction. Certainly with this current transaction manager it is not achievable. I have also checked the source code of ViewPager for Android Lollipop and still this issue is not resolved.
Work around:
I have come up with a workaround and customized these api of android sdk.
1)      ViewPager
2)      PagerAdapter
3)      FragmentPagerAdapter
I have created a jar and can be downloaded here. As of now the onResume,onPause of all the fragments in the viewpager will be called as per the flow.