即使在FragmentManager.executePendingTransactions()之后,也不会立即调用Fragment中的onCreateView()

时间:2013-06-21 07:04:57

标签: java android fragment

我读过如果我们需要立即创建片段,我们必须在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()。我根本没有弄乱线程。

1 个答案:

答案 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
}