如何完全销毁对话框片段以解决内存泄漏问题? [英] How to destroy a dialog fragment completely for memory leak issue?

查看:68
本文介绍了如何完全销毁对话框片段以解决内存泄漏问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个空的对话框片段.为了解决内存泄漏问题,我将 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:

ScreenShot

我尝试在 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();

这篇关于如何完全销毁对话框片段以解决内存泄漏问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆