Fragments in ViewPager

Using ViewPager with FragmentPagerAdapter or FragmentStatePagerAdapter appears to be quite easy and enjoyable.

It could be done within few simple steps:

  1. Create layout .xml resource with ViewPager
  2. Create adapter and implement all required methods
  3. Set adapter instance to your ViewPager instance.

Simple? Yes! – but like always only for easiest (also the most common) case

Problem occurs when we want to make something more sophisticated, i.e. add fragments dynamically – provide fragments/pages to adapter from its outside.

The Code

Take a look at quite popular AppIntro library. It gives user a possibility to simply create an app intro just by extending  one AppIntro Activitiy.
One extend, few Fragment slides added in init method, and we got it!

So…the idea of this AppIntro library is to separate and take off weight from a developer to manage all those adapters and viewpagers.

Look in the source code can bring us closer to a basic concept (as I could only imagine it) of this library

Every activity onCreate() callback method calls init(savedInstanceState) method to give a user possibility to add fragments/slies which later are used in FragmentPagerAdapter class.


So it looks like all good at the beginning, but yellow light may light up in the head of the developer.


Creating/providing new fragments instances every time in onCreate() method.

Do you remember what we are doing when we want to create and just add single a fragment to our Activity?

We are checking if this is the first run or recreation after a configuration change.

After orientation change all fragments currently added to FragmentManager are automatically restored and instantiated so there is no need to create them once again.

Same thing is with the ViewPager and FragmentPagerAdapter. Once the adapter adds a fragment to FragmentManager after rotation it will not call getItem(int position) adapter method, but it will look for an already recreated Fragment in FragmentManager.

Line 11 – finding from manager, and only if the fragment is not yet there Line 16 gets new fragment instance from getItem() method



We should always remember about the automatic fragment restoration process done via FragmentManager with companion of Activity implementation.

Provide fragments only once at the beginning or only when they are needed (in case of an adapter and getItem(int position) method call) not every time redundantly.



Michał Łuszczuk

Lead Android developer @Blix-Qpony Group