How to destroy a dialog fragment completely for memory leak issue?

泪湿孤枕 提交于 2020-04-16 04:53:12

问题


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");

and close it, LeakCanary show me this Error:

ScreenShot

I try and add setRetainInstance in OnCreate method and view = null in onDestroyView. But that memory leak error still showing.

This is my Fragment:

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;
}
}

How to fix this issue?


回答1:


you can open dialog like this:

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(TabsFragment.newInstance(), "Fragment");
ft.addToBackStack(null);
ft.commit();

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();


来源:https://stackoverflow.com/questions/60918546/how-to-destroy-a-dialog-fragment-completely-for-memory-leak-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!