Android 中關於Fragment嵌套Fragment的問題

轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/5802146.html html

問題描述:佈局

在項目中Activity A中嵌套Fragment B,Fragment B中再嵌套Fragment C,如圖:spa

 

問題1:在點擊Activity A中主菜單1進行切換時,報錯Fragment C already added。code

解決:在Framgent B中添加Fragment C 調用add()時先判斷fragmentC.isAdded()htm

FragmentManager fm=getActivity().getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
if(!sub1Fragment.isAdded()){
    ft.add(R.id.rl_fragment_container, sub1Fragment).commit();
}

問題2:修改後發現,Fragment C佈局添加失敗,同時切換主菜單2時,報錯。blog

解決:這是Fragment的嵌套問題。FragmentB中的嵌套不能再用getActivity().getSupportFragmentManager();要用getChildFragmentManager();get

即上面代碼應改成:it

FragmentManager fm=getChildFragmentManager(); 
FragmentTransaction ft
=fm.beginTransaction();
if(!sub1Fragment.isAdded()){   ft.add(R.id.rl_fragment_container, sub1Fragment).commit(); }
相關文章
相關標籤/搜索