时间:2023-03-01 15:10:41 | 栏目: | 点击:次
问题描述:
在项目中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(); }