3

I have many doubts about how correctly use FragmentPagerAdapter. Not about how to create the adapter or implements the methods, it is more related to how the underlying fragments should manage the instantiated views.

In the Android API about FragmentPagerAdapter, it is clearly stated the following:

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.

So it can be assumed that the view returned by a fragment in its own onCreateView, can be disposed by Android. It is also noticeable how when you have more than 3 pages and switch between them, the onCreateView of each fragment is called more than one time for the same fragment instance. The exmple given in the FragmentPagerAdapter API seems perfect with this approach:

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText("Fragment #" + mNum);
        return v;
    }

Notice how in this example it is not kept any reference to instantiated views in the Fragment itself. However it is often required to save the instantiated view references for further updating the interface with user interactions. In such case, I suppose that the view hierarchy will not be destroyed as suggested in the documentation (as the fragment state is not destroyed).

Is in this case legitime to save the instantiated view and return then again in the next onCreateView?

Is it better to use setOffscreenPageLimit from ViewPager for increasing the number of pages kept in memory rather than reuse views?

Al my doubts arise as the documentation suggests that the view hierarchy can be destroyed, but if you keep any view reference in the Fragment... they cannot be destroyed by the garbage collector. I am right?

Alvaro Luis Bustamante
  • 8,157
  • 3
  • 28
  • 42

0 Answers0