executePendingTransactions

executePendingTransactions

本文介绍了onCreateView()的片段是不会立即叫,即使FragmentManager.executePendingTransactions()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看,如果我们需要立即创建片段,我们要调用 executePendingTransactions() FragmentManager 方法。好了,这就是我想要做的。像这样的:

I read that if we need to create fragment immediately, we have to call executePendingTransactions() method on FragmentManager. Well, that's what I'm trying to do. Like this:

@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()。正如你看到的,我打电话 executePendingTransactions()在UI线程所应当的。我不是搞乱这里线程的。

I'd like to know why foo() method is called BEFORE MyFragment's onCreateView(). As you see, I'm calling executePendingTransactions() in UI Thread as it should be. I'm not messing here with threads at all.

推荐答案

我碰到了同样的问题,我发现,如果我跑一样fragmentTransaction code从OnStart方法中,执行工作正常。我不知道有足够的了解Android的生命周期来看就知道为什么是这样的情况下,虽然。

I ran into the same issue and I found that if I ran the same fragmentTransaction code from within the onStart method, the execution worked as expected. I do not know enough about the Android view lifecycle to know why this is the case though.

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
}

这篇关于onCreateView()的片段是不会立即叫,即使FragmentManager.executePendingTransactions()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 20:48