Home Ask Login Register

Developers Planet

Your answer is one click away!

Highway62 February 2016

Android memory leak issue when using ViewPagerAdapter with nested fragments

I have a fragment, fragment A, which holds a ViewPager. The ViewPager loads different fragments which the user can swipe through "indefinitely" (I use a really high number of pages/loops to emulate this). When a user clicks on the current ViewPager fragment, then fragment A with the ViewPager is replaced by fragment B in the fragment manager. When the user returns from fragment B, the backstack is popped using popBackStackImmediate(). If the user repeats this action several times, the heap begins to fill up by about 100kb at a time until the app starts to become sloppy and malfunction as the memory fills up. I'm unsure what exactly is causing this, can anyone help?

My fragment A with the ViewPager:

public class MainFragment extends Fragment {

    private MainWearActivity mMainWearActivity;
    View view;

    private int currentPage;
    private ViewPager pager;
    private ViewPagerAdapter adapter;
    private LinearLayout helpIcons;

    public void onCreate(Bundle savedInstanceState) {
        mMainWearActivity = (MainWearActivity) getActivity();
        adapter = new ViewPagerAdapter(this.getChildFragmentManager());

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_main, container, false);

        // Scrolling menu
        pager = (ViewPager) view.findViewById(R.id.watchNavPager);
        // Set current item to the middle page
        currentPage = Consts.FIRST_PAGE;
        // Set number of pages
        // Set no margin so other pages are hidden

        return view;

    public void onDestroyView() {
        pager = n        


Sergey Trukhachev February 2016

There is a specific PagerAdapter for your needs - FragmentStatePagerAdapter

This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.

Post Status

Asked in February 2016
Viewed 2,542 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life