7

My simple layout only has a fragment placeholder:

<FrameLayout
   android:id="@+id/fragment_placeholder"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
  />

I firstly add a 1st fragment to this placeholder:

fragmentTransaction.add(R.id.fragment_placeholder, firstFragment, "first"); //I did not put to backstack

I have a 2nd fragment, which replace the above fragment and put it to back stack:

FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction fragTrans = fragMgr.beginTransaction();

//initialize an fragment instance
Fragment secondFragment = initSecondFragment(); 

//replace with the fragment 
fragTrans.replace(R.id.fragment_placeholder, secondFragment, "second");

//Add transaction to back stack
fragTrans.addToBackStack(null);

//commit the transaction
fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragTrans.commit();  

//The following log returns me 0 when counting the number of fragments in back stack, why?  
Log.v("nr of fragment in back stack", fragMgr.getBackStackEntryCount()+"");

But I end up with 0 fragment in back stack, why???

Leem.fin
  • 40,781
  • 83
  • 202
  • 354

3 Answers3

4

Try executePendingTransactions() before the Log to ensure that the commit it happens. Like this:

fragMgr.executePendingTransactions();
Log.v("nr of fragment in back stack", fragMgr.getBackStackEntryCount()+"");

Hope it helps...

FrankenBel
  • 86
  • 5
0

I'm not sure in answer ... May be need wait that fragment was added ? Try to get count by this

 new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.v("nr of fragment in back stack", fragMgr.getBackStackEntryCount()+"");  
            }
        },50);
dooplaye
  • 999
  • 13
  • 28
  • You should not be using timers to listen to this type of changes... What if the transaction took longer than 50ms? – tf.alves Aug 31 '15 at 13:36
  • @tf.alves i know it is dirty solution, but it works for me. May be you have a better suggestion? – dooplaye Oct 10 '15 at 18:41
  • @dooplaye, unfortunately no, but, as a rule of thumb, you should never rely on a timer with a random interval. About the problem at hand, I think the wrong fragment manager may be at cause, maybe he should be dealing with the child fragment manager – tf.alves Oct 10 '15 at 18:52
0

try this for the first fragment

fragmentTransaction.addToBackStack(null).add(R.id.fragment_placeholder, firstFragment, "first"); 

and this for the second fragment

fragmentTransaction.addToBackStack(null).replace(R.id.fragment_placeholder, secondFragment, "second");