I have just started to use LeakCanary and when I replace a Fragment, every time leaks increase. This is the LeakCanary report:
android.widget.LinearLayout instance
ā Leaking: YES (ObjectWatcher was watching this because com.home.app1.PostFragment received Fragment#onDestroyView() callback
(references to its views should be cleared to prevent leaks))
This is my Fragment Replace code:
public void change(Fragment fragment) {
((FragmentActivity) context).getSupportFragmentManager().beginTransaction()
.replace(R.id.frameLayout, fragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
}
So I research on SO and some people say views must be clenead in onDestroyView. Then I tried this in onDestroyView: fragmentView=null; but nothing was changed. Also tried this:
if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
But again nothing was changed. So I tried to make all views null like below:
@Override
public void onDestroyView() {
super.onDestroyView();
backButton=null;
swipeLayout=null;
imageView=null; ...etc.
}
Eventually leaking warnings on LeakCanary disappeared. But I think this is not a solution and does not make sense because there may be many views. So what's the solution to avoid this leaks? Thanks.