onCreateView() in Fragment is not called immediate

2019-02-08 01:25发布

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()
}

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.

1条回答
混吃等死
2楼-- · 2019-02-08 01:47

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
}
查看更多
登录 后发表回答