0

当第二次调用 onCreateView 时,它会添加另一个 MyFragment 实例。例如,当这个 Fragment 从回栈返回时,它会显示 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;
}
4

1 回答 1

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

于 2013-03-18T11:28:42.127 回答