Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-lifecyclefragment-lifecycle

Do I have to set views to null in `onDestroyView()` for Fragments when used inside a ViewPager?


If I have a FragmentStatePagerAdapter with a many Fragments like this:

public class MyFragment extends Fragment {
    View myView;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState {
        myView =  view.findViewById(R.id.my_view);
    } 
}

Now suppose I scroll to some other page...does this leak the destroyed views of other pages that are off screen(Because I have a ref to them - myViews)?

Does doing this help:

@Override
public void onDestroyView() {
    myView = null;
}

Solution

  • No need. FragmentStatePagerAdapter takes care of destroying the Fragment automatically. Since the myView reference is inside the Fragment and it's not static, it will be destroyed as well.

    FragmentStatePagerAdapter doc:

    https://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html

    When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment

    Be aware that this holds 3 fragments (if available) in memory without destroying, by default. The one that is currently being displayed on the screen, the one on the left and the one on the right to the current fragment. You can customize that count though.