Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace fragment C with fragment A when back button is pressed?

My scenario : Activity 1 consists of Fragments A-> B-> C. All the fragments are added using this code :

        FragmentManager fm = getSupportFragmentManager();         FragmentTransaction ft = fm.beginTransaction();         ft.replace(R.id.content, fragment, TAG);         ft.addToBackStack(TAG);         ft.commit(); 

Now, from fragment C, I want to directly return to Fragment A. Therefore, I've commented ft.addToBackStack(TAG) while adding Fragment C. So when I press back button from C I directly get Fragment A on the screen.

However, Fragment C is not replaced by A. In fact, both the fragments are visible. How do I solve this issue?

like image 741
Harshal Kshatriya Avatar asked Dec 21 '12 05:12

Harshal Kshatriya


People also ask

How do I replace a fragment in a fragment?

Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container. transaction. commit();

When replacing a fragment with another one how do you know that the user can get back to the last fragment when they press the back button?

The title of the toolbar should change between the two fragments (from "First Fragment" to "Second Fragment"). The second fragment should have a "back button" (arrow left icon) in the toolbar that, on click, lets the user go back to the first fragment.

Which method is called when fragment is replaced?

But you can create your own interface called Replaceable with a method onReplace() that you have your fragment implement, and call it directly when you call FragmentTransaction. replace() .


1 Answers

You need to do 2 things - name the FragmentTransaction from A->B and then override onBackPressed() in your containing activity to call FragmentManager#popBackStack (String name, int flags) when you are on Fragment C. Example:

Transition from A->B

getSupportFragmentManager()   .beginTransaction()   .replace(R.id.container, new FragmentB(), "FragmentB")   .addToBackStack("A_B_TAG")   .commit(); 

Transition from B->C will use a similar transaction with "FragmentC" as its tag.

Then in your containing Activity override onBackPressed():

@Override public void onBackPressed() {   if (getSupportFragmentManager().findFragmentByTag("FragmentC") != null) {     // I'm viewing Fragment C     getSupportFragmentManager().popBackStack("A_B_TAG",       FragmentManager.POP_BACK_STACK_INCLUSIVE);   } else {     super.onBackPressed();   } } 
like image 168
user697495 Avatar answered Sep 21 '22 06:09

user697495