当在Activity里面有多个fragment的时候,来回切换fragment,会造成内存使用一直在增加。
由于fragment在调用remove之后,里面的view的引用导致内存回收不了,造成内存泄露,所以不断的new Fragment切换之后,内存使用一直在增加。
解决办法:
在BaseFragment类里面的onDestroyView()方法里面调用如下方法
private void unbindDrawables(View view)
{
if (view.getBackground() != null)
{
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup && !(view instanceof AdapterView))
{
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
{
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
例如:
@Override
public void onDestroyView() {
super.onDestroyView();
unbindDrawables(getView());
}
如有错误,请指正。