ViewPager with detailed fragment lifecycle (onResumeFragment) [including source code]

2 11 2013

When using ViewPager introduced in this ViewPager tutorial you may encounter some issue connected with fragment and ViewPager lifecycle. The fragment’s lifecycle is connected with activity lifecycle. Some methods like onAttach() are added, but the general rule is the same.

ViewPager manages its fragments in a bit different way. Fragment’s onResume() is not called when fragment is actually resumed and showed to the user on screen. So in standard ViewPager it is impossible to update fragment when it is displayed, since there is no lifecycle method that is called when fragment is displayed.

ViewPager actually loads three fragments at once, calling their onResume(). It loads the visible fragment ant both of its neighbours (the one on the left and one on the right. It is needed for fluent sliding between fragments. It is painful when the content on the first fragment depends, and should be updated when fragment is resumed.

You can easily see how onResume() and onPause() are called in fact just by logging these method calls in Logcat. And how to have true fragment’s lifecycle I will show in this tutorial.

Note: Whole tutorial is based on the ViewPagerTutorial from this post.

Download source code!

You are welcome to download and use the source code from this tutorial as You need. Here it is!

1. Create LifecycleManager Interface
The interface will have two methods and each ViewPager’s Fragment will implement it. These methods Are as follows:

public interface FragmentLifecycle {

	public void onPauseFragment();
	public void onResumeFragment();


2. Let each Fragment implement the interface
Add iplements statement for each class declaration:

public class FragmentBlue extends Fragment implements FragmentLifecycle 
public class FragmentGreen extends Fragment implements FragmentLifecycle 
public class FragmentPink extends Fragment implements FragmentLifecycle

3. 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:

public void onPauseFragment() {
	Log.i(TAG, "onPauseFragment()");
	Toast.makeText(getActivity(), "onPauseFragment():" + TAG, Toast.LENGTH_SHORT).show(); 

public void onResumeFragment() {
	Log.i(TAG, "onResumeFragment()");
	Toast.makeText(getActivity(), "onResumeFragment():" + TAG, Toast.LENGTH_SHORT).show(); 

4. Call interface methods on ViewPager page change
You can set OnPageChangeListener on ViewPager and get callback each time when ViewPager shows another page:


5. 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() {

	int currentPosition = 0;

	public void onPageSelected(int newPosition) {

		FragmentLifecycle fragmentToShow = (FragmentLifecycle)pageAdapter.getItem(newPosition);

		FragmentLifecycle fragmentToHide = (FragmentLifecycle)pageAdapter.getItem(currentPosition);

		currentPosition = newPosition;

	public void onPageScrolled(int arg0, float arg1, int arg2) { }

	public void onPageScrollStateChanged(int arg0) { }

6. That’s all – download source code!

You are welcome to download and use the source code from this tutorial as You need. Here it is!

Did I help you?

I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality Donate Button with Credit Cards Thank You!




19 responses

2 11 2013
Android (support v4) ViewPager tutorial (including source code) | Looks OK!

[…] this post to see how to manage fragment’s lifecycle – detect when fragment is shown to the […]

7 02 2014

Wow, this worked great. I can’t believe it. Thank you so much.

22 02 2014

do you find that onPageSelected method won’t be called when show the first page?

22 02 2014
Jacek Milewski

Good question!

May not be, I am not sure. But in this case you know exactly which page is going to be shown, so you can implement your logic accordingly on first call.

12 06 2014

my onResume and onPause are correctly called… but I think that this is happening when the fragment isn’t attached to the activity.. i keep getting nullPointer on getActivity() method…

6 02 2017

I am having the same problem, did you find a solution?

2 10 2017

You might have your adapter returning a new instance of a fragment in getItem(). Create fragment instances in adapter’s constructor and store them in something like a cache (e.g ArrayList). getItem() than return from that cache instead of creating new instances.

9 01 2015
hemant shori

hi i need help .
i am implementing a view pager in a fragment1 and when i change to fragment2 and go back to fragment1 the content of the viewpager vanishes i have used notifydatasetchange() it is not working here please help.
any way to refresh the fragment of the view pager .

23 12 2015
Mahesh Parate

you can set the viewpager offset limit.


its not refresh but it holding the view in pause state.

9 01 2016
Jacek Milewski


28 01 2015

Reblogged this on shebella1014.

28 01 2015

Very good!

2 03 2015

It’s great!
If fragments extends BaseFragment, we can implement listener once on BaseFragment.

19 03 2015
Albert Sonne

Brilliant solution dude! I really like that! Very helpful, simple and clean code. Мy admiration!

11 05 2015

You are brilliant O:) thanks for making this tutorial….
I have small question why this application gives error in landscape mode, please help me…..
Thanks once again :)

14 05 2015

actually the default value to load fragments into viewpager is 2, not 3

4 08 2017
Rahul Kumar

use addOnPageChangeListener instead of setOnPageChangeListener :)

4 01 2018

Gracias My friend.. me sirvio mucho tu informacion ..

8 02 2018
How to go from adapter to a fragment and how to integrate the SwipRefresh – program faq

[…] sachant que j’ai utliser Drawlayoute pour naviguer entre fragments(InitialHomeFragment,MyProfileFragment,My_activitiesFragment…) et j ‘ai utliser View page et tabLayout dans InitialHomeFragment pour passer entre les fragment (HomeFragment,AnnouncementFragment()…) J’ai utiliser ce lien pour le deuxième problème mais ne savoirs pas comment changer Fragment en FragmentActivity… […]

Give Your feedback:

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: