Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

popBackStack() after addToBackStack does not work

My project contains two fragment :

  • FragmentA : the fragment loaded by default when the app starts
  • FragmentB : replace the fragmentA when a click on a button is done.

This is the XML of my main view :

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent">      <fragment         android:id="@+id/main_fragment_container"         android:name="fragmentA"         android:layout_width="match_parent"         android:layout_height="match_parent">     </fragment>  </LinearLayout> 

When I wish to replace the FragmentA by the FragmentB, I use this code :

FragmentTransaction fragmentTransaction = getSupportFragmentManager()             .beginTransaction(); fragmentTransaction.addToBackStack(null); fragmentTransaction.replace(R.id.main_fragment_container, new FragmentB()); fragmentTransaction.commit(); 

This code works fine. My FragmentA is replaced by the new FragmentB. But when a click is done on the back button, I wish replace the FragmentB by the FragmentA by using popBackStackImmediate().

This is the code I use:

if (getSupportFragmentManager().getBackStackEntryCount() > 0){     boolean done = getFragmentManager().popBackStackImmediate();     fragmentTransaction.commit(); } 

The function popBackStackImmediate return always false and the FragmentB still in foreground.

Why the FragmentA does not replace the FragmentB when I call popBackStackImmediate ? Is anybody has an idea to solve my problem?

thanks in advance

like image 923
reevolt Avatar asked Jan 16 '14 07:01

reevolt


1 Answers

You use the getSupportedFragmentManager() to replace FragmentA by FragmentB. But you call popBackStack() on the getFragmentManager().

If you are adding the Fragments to the android.support.v4.app.FragmentManager you also have to call popBackStack() on the same FragmentManager.

This code should solve the problem:

if (getSupportFragmentManager().getBackStackEntryCount() > 0){     boolean done = getSupportFragmentManager().popBackStackImmediate(); } 
like image 162
owe Avatar answered Sep 21 '22 21:09

owe