2015-12-21 49 views
0

我得到含子片段B.如何正確的方法來創建和碎片A添加子B片段,使任何Android的神奇作品片段的?分片嵌套自動創建

目前我在片段A的構造函數初始化子B片段,並將其添加在片段A(通過FragmentTransaction.replace)的onCreateView 也能正常工作的第一次。但是,如果片段被暫停/恢復片段調用構造函數,創建子片段B並且另外android會自動創建子片段B.所以有2個孩子片段B ...我認爲最好以某種方式使用從android創建的孩子片段B.

回答

0

您可以檢查Fragment B是否存在

Fragment b = fragmentManager.findFragmentById(R.id.fragment_b_container); 
    if(b == null) { 
    //initialize the fragment transaction here... 
    } 
+0

能否請您補充信息,其中的代碼應該是什麼?絕對不在構造函數中。也許onCreate或onCreateView? –

+0

你在哪裏調用嵌套片段? (onCreateView) –

+0

現在我檢查savedInstanceState在onCreateView,如果!= NULL getChildFragmentManager()。findFragmentByTag( 「TAG」)。否則用新的FragmentB()初始化片段。初始化應改爲FragmentB.getNewInstance()據我記得......更重要的是什麼正確的方式,使Android的框架魔不工作? –