如何完全销毁对话框片段以解决内存泄漏问题?
问题描述:
我有一个空的对话框片段.为了解决内存泄漏问题,我将 LeakCanary 库添加到我的应用中.使用以下命令打开对话框片段时:
I Have a empty dialog fragment. For get memory leak issue, I Add LeakCanary library to my app. When open dialog fragment with this commands:
DialogFragment fragment = TabsFragment.newInstance();
fragment.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.DialogFragments);
fragment.show(getSupportFragmentManager(), "MyFragment");
并关闭它,LeakCanary向我显示此错误:
and close it, LeakCanary show me this Error:
我尝试在 OnCreate 方法中添加 setRetainInstance ,并在 onDestroyView 中添加 view = null .但是该内存泄漏错误仍然显示.
I try and add setRetainInstance in OnCreate method and view = null in onDestroyView. But that memory leak error still showing.
这是我的片段:
public class TabsFragment extends DialogFragment {
private View view;
public static TabsFragment newInstance() {
return new TabsFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.my_fragment, container, false);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
dismiss();
view = null;
}
}
如何解决此问题?
答
您可以打开如下对话框:
you can open dialog like this:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(TabsFragment.newInstance(), "Fragment");
ft.addToBackStack(null);
ft.commit();
然后在对话框片段的onDismiss方法中,编写以下代码:
And in onDismiss method in your dialog fragment, Write this codes:
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.getBackStackEntryCount() > 0)
fragmentManager.popBackStack();
fragmentTransaction.commit();