7

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

<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个片段,为什么???

4

3 回答 3

4

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

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

希望能帮助到你...

于 2014-03-01T21:14:08.193 回答
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);
于 2014-03-01T20:45:40.013 回答
0

第一个片段试试这个

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

这是第二个片段

fragmentTransaction.addToBackStack(null).replace(R.id.fragment_placeholder, secondFragment, "second");
于 2020-12-06T18:07:51.420 回答