executePendingTransactions

executePendingTransactions

我读到,如果需要立即创建片段,则必须在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()方法被称为MyFragmentonCreateView()之前。如您所见,我正在UI线程中按原样调用executePendingTransactions()。我完全不会在这里弄乱线程。

最佳答案

我遇到了同样的问题,发现如果我从onStart方法中运行了相同的fragmentTransaction代码,则执行工作将按预期进行。我对Android View 生命周期了解不足,但是为什么会这样。

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
}

关于java - 即使在FragmentManager.executePendingTransactions()之后,也不会立即调用Fragment中的onCreateView(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17229500/

10-10 09:42