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;

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

    @Override
    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);
        pager.setAdapter(adapter);
        pager.addOnPageChangeListener(adapter);
        // Set current item to the middle page
        pager.setCurrentItem(Consts.FIRST_PAGE);
        currentPage = Consts.FIRST_PAGE;
        // Set number of pages
        pager.setOffscreenPageLimit(4);
        // Set no margin so other pages are hidden
        pager.setPageMargin(0);

        return view;
    }


    @Override
    public void onDestroyView() {
        pager = n        

Answers


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

Search




Leave an answer