轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/5802146.html 問題描述: 在項目中Activity A中嵌套Fragment B,Fragment B中再嵌套Fragment C,如圖: 問題1:在點擊Activity A中主菜單1進行切換時,報錯 ...
轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/5802146.html
問題描述:
在項目中Activity A中嵌套Fragment B,Fragment B中再嵌套Fragment C,如圖:
問題1:在點擊Activity A中主菜單1進行切換時,報錯Fragment C already added。
解決:在Framgent B中添加Fragment C 調用add()時先判斷fragmentC.isAdded()
FragmentManager fm=getActivity().getSupportFragmentManager(); FragmentTransaction ft=fm.beginTransaction(); if(!sub1Fragment.isAdded()){ ft.add(R.id.rl_fragment_container, sub1Fragment).commit(); }
問題2:修改後發現,Fragment C佈局添加失敗,同時切換主菜單2時,報錯。
解決:這是Fragment的嵌套問題。FragmentB中的嵌套不能再用getActivity().getSupportFragmentManager();要用getChildFragmentManager();
即上面代碼應改為:
FragmentManager fm=getChildFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
if(!sub1Fragment.isAdded()){
ft.add(R.id.rl_fragment_container, sub1Fragment).commit();
}