为什么在backstack中零碎片

时间:2012-04-20 13:53:20

标签: android android-layout android-intent android-emulator android-fragments

我的简单布局只有一个片段占位符:

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

我首先在此占位符中添加第一个片段

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

我有一个第二个片段,它取代了上面的片段,将它放回到堆栈

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()+"");

但我最后在后面的堆栈中使用 0 片段,为什么???

3 个答案:

答案 0 :(得分:4)

在Log之前尝试执行executePendingTransactions()以确保提交它。 像这样:

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

希望它有所帮助...

答案 1 :(得分:0)

我不确定答案......可能需要等待添加片段吗? 试着通过这个来计算

 new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.v("nr of fragment in back stack", fragMgr.getBackStackEntryCount()+"");  
            }
        },50);

答案 2 :(得分:0)

尝试第一个片段

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

第二个片段

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