1

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;
}
Adil Saiyad
  • 1,582
  • 2
  • 17
  • 34
Veneet Reddy
  • 2,707
  • 1
  • 24
  • 40

1 Answers1

4

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.

Bob
  • 13,447
  • 7
  • 35
  • 45