【发布时间】:2020-05-12 04:31:08
【问题描述】:
我刚刚开始使用 LeakCanary,当我更换 Fragment 时,每次泄漏都会增加。这是 LeakCanary 报告:
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))
这是我的片段替换代码:
public void change(Fragment fragment) {
((FragmentActivity) context).getSupportFragmentManager().beginTransaction()
.replace(R.id.frameLayout, fragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
}
所以我研究了 SO,有人说必须在onDestroyView 中清除视图。然后我在onDestroyView:fragmentView=null; 中尝试了这个,但没有任何改变。也试过这个:
if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
但还是没有任何改变。所以我试图让所有视图都为空,如下所示:
@Override
public void onDestroyView() {
super.onDestroyView();
backButton=null;
swipeLayout=null;
imageView=null; ...etc.
}
LeakCanary 上的泄漏警告最终消失了。但我认为这不是一个解决方案,没有意义,因为可能有很多意见。那么避免这种泄漏的解决方案是什么?谢谢。
【问题讨论】:
-
请添加您的泄漏跟踪
标签: java android android-fragments memory-leaks leakcanary