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

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:

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

@Override
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:

pager.setOnPageChangeListener(pageChangeListener);

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;

	@Override
	public void onPageSelected(int newPosition) {

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

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

		currentPosition = newPosition;
	}

	@Override
	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!

22 thoughts on “ViewPager with detailed fragment lifecycle (onResumeFragment) [including source code]

    1. 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.

  1. 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…

      1. 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.

  2. 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 .

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

  4. To use the current one. thanks for the explanation
    I used this

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    int currentPosition = 0;

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    FragmentLifecycle fragmentLifecycleToShow =(FragmentLifecycle) viewPager.getAdapter().instantiateItem(viewPager, viewPager.getCurrentItem());
    fragmentLifecycleToShow.onResumeFragment();

    FragmentLifecycle fragmentLifecycleToHide =(FragmentLifecycle) viewPager.getAdapter().instantiateItem(viewPager, currentPosition);
    fragmentLifecycleToHide.onPauseFragment();

    currentPosition = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    });

Give Your feedback: