为什么多次添加OnCreateView子片段?

时间:2013-03-18 11:14:28

标签: android android-fragments

当onCreateView第二次调用时,它会添加另一个MyFragment实例。例如,当此片段从后台堆栈返回时,它会显示两个MyFragment实例。为什么?我应该如何预防?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.announcement, null);
 FragmentTransaction fragmentTransaction = getChildFragmentManager()
            .beginTransaction();
 fragmentTransaction.add(R.id.fragmentContainer, new MyFragment());
 fragmentTransaction.commit();
 return view;
}

1 个答案:

答案 0 :(得分:2)

FragmentTransaction应该在onCreate中完成:

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 FragmentTransaction fragmentTransaction = getChildFragmentManager()
        .beginTransaction();
 fragmentTransaction.add(R.id.fragmentContainer, new MyFragment());
 fragmentTransaction.commit();
}

感谢Atrix1987