Skip to content Skip to sidebar Skip to footer

Removing A Fragment From A Fragment

I have an Activity that creates a Fragment and then this Fragment creates another Fragment: Activity -> Fragment1 -> Fragment2 I am now in Fragment2 and I'd like to go back t

Solution 1:

@AhmedAbidi has a nice insight to your problem and yes, implementing popBackStack properly may solve your problem. But anyway, I would like to suggest a different approach to handle this type of situations.

Write two public functions in your Activity to switch between your fragments.

public void switchToFragment1() {
    getSupportFragmentManager().beginTransaction()
        .replace(R.id.fragment_container, new Fragment1()).commit();
}

public void switchToFragment2() {
    getSupportFragmentManager().beginTransaction()
        .replace(R.id.fragment_container, new Fragment2()).commit();
}

Now from the button click in your Fragment1 you might launch the Fragment2 via,

((YourActivity) getActivity()).switchToFragment2();

And the same thing while switching to Fragment1

((YourActivity) getActivity()).switchToFragment1();

Solution 2:

Your question needs more code for clarity.

Is Fragment1 adding Fragment2 via getSupportFragmentManager() or getChildFragmentManager()? Presumably it appears you are doing the former, and if so, you are incorrectly using the Fragment API. Fragments are not supposed to know about each other, per Android's Fragment Documentation:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

You should therefore implement the appropriate listeners to communicate from Fragment1 to Activity, which can then decide where/when to add Fragment2 -- then properly utilize the back stack functionality of getSupportFragmentManager().addToBackStack()... with getSupportFragmentManager().popBackStack(). See Android Documentation on Back Navigation for Fragments for further explanation.

Post a Comment for "Removing A Fragment From A Fragment"