I have developed a small API for dialog fragments based on Google support library with very simple requirements:
- API could add (or replace) a modal dialog
- API could dismiss dialog programmatically or user can dismiss dialog by pressing button
Does my API creates a memory leakage by constantly adding fragments to backstack?
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();
}
}
}
}