我开发了一个基于Google支持库的对话框片段的小API,其要求非常简单:
我的API是否通过不断向反叠堆添加片段来创建内存泄漏?
public class DialogFragmentUtils {
private static final String DIALOG_TAG = "dialogTag";
public static void showDialogFragment(@Nullable Activity activity, @NotNull Fragment fragment) {
if (activity instanceof FragmentActivity) {
FragmentActivity fragmentActivity = (FragmentActivity) activity;
FragmentManager fm = fragmentActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(DIALOG_TAG);
if (prev != null && prev.isAdded()) {
ft.remove(prev);
}
ft.add(fragment, DIALOG_TAG);
ft.addToBackStack(null);
ft.commit();
}
}
public static void dismissDialogFragment(@Nullable Activity activity) {
if (activity instanceof FragmentActivity) {
FragmentActivity fragmentActivity = (FragmentActivity) activity;
FragmentManager fm = fragmentActivity.getSupportFragmentManager();
DialogFragment dialog = (DialogFragment) fm.findFragmentByTag(DIALOG_TAG);
if (dialog != null) {
dialog.dismiss();
}
}
}
}
答案 0 :(得分:4)
是的,它容易出现内存不足,而不是内存泄漏。所有后向堆栈Fragment
都使用硬引用保存在内存中。因此,如果你在后台堆叠中保留了大量的Fragment
s,那么你将会失去记忆。
看看这里:When a Fragment is replaced and put in the back stack (or removed) does it stay in memory?
更新:我发现您的DIALOG_TAG
没有变化,因此您一次只能在后台堆叠中保留一个Fragment
,因为如果存在,则删除旧的{{1}}。在这种情况下,您可能没有内存不足的问题。
答案 1 :(得分:3)