我读过如果我们需要立即创建片段,我们必须在executePendingTransactions()
上调用FragmentManager
方法。嗯,这就是我想要做的。像这样:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.layout.fragmentContainer, new MyFragment);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
foo(); // It is called before MyFragment's onCreateView()
}
我想知道为什么在foo()
MyFragment
之前调用onCreateView()
方法。如您所见,我正在UI线程中调用executePendingTransactions()
。我根本没有弄乱线程。
答案 0 :(得分:17)
我遇到了同样的问题,我发现如果我在onStart方法中运行相同的fragmentTransaction代码,则执行按预期工作。我对Android视图生命周期知之甚少,不知道为什么会出现这种情况。
public void onStart() {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.layout.fragmentContainer, new MyFragment);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
foo(); // Should now work correctly
}