How to replace DialogFragment with another DialogFragment?

We add general / normal Fragmentprogrammatically, doing something like:

fragmentTransaction.add(containerViewId, fragmentToAdd, fragmentTag);

and replace a Fragmentwith another by doing something like:

fragmentTransaction.replace(containerViewId, newFragment, tagOfNewFragment);

But we add on DialogFragment

dialogFramentInstance.show(fragmentManager, fragmentTag);

The question is how to replace this DialogFragmentone that was added by the method show()?

+7
source share
4 answers
dialogFramentInstance.show(fragmentManager, fragmentTag);

It simply adds a portion of the dialog box to the box using an add transaction (without container).

To replace the fragments, you will need a container, and since you do not have one, the dismiss()first and show()new will be the only option .

+2
private void closeYourDialogFragment() {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    Fragment fragmentToRemove = getSupportFragmentManager().findFragmentByTag("your_dialog_fragment");
    if (fragmentToRemove != null) {
        ft.remove(fragmentToRemove);
    }
    ft.addToBackStack(null);
    ft.commit(); // or ft.commitAllowingStateLoss()
}

private void replaceYourDialogFragment() {
    closeYourDialogFragment();

    YourDialogFragment yourDialogFragment = new YourDialogFragment();
    yourDialogFragment.show(getSupportFragmentManager(), "your_dialog_fragment");
}
+1

, :

    public void showFragment(Fragment fragment) {
    if (fragment instanceof DialogFragment) {
        FragmentTransaction ft = mContext.getFragmentManager().beginTransaction();
        Fragment prev = mContext.getFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            Log.d(TAG, "showFragment: remove prev...." + prev.getClass().getSimpleName());
            ft.remove(prev);
        }
        mContext.getFragmentManager().executePendingTransactions();
        if (!fragment.isAdded()){
            ft.addToBackStack(null);
            ((DialogFragment) fragment).show(ft, "dialog");
        } else {
            Log.w(TAG, "showFragment: fragment has been added!" );
        }
    }
}
0

, .

, , , .

: Manager, . , Activity (supportFragmentManager) (childFragmentManager), , .

-1

All Articles