Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onCreateView() in Fragment is not called immediately, even after FragmentManager.executePendingTransactions()

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.

like image 482
Piotr Chojnacki Avatar asked Jun 21 '13 07:06

Piotr Chojnacki


People also ask

What is onCreateView fragment?

onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.

When onviewcreated is called?

oncreate view instantiates the view, onviewcreated is called after oncreateview and before saved states are restored... it's more a timing issue in the lifecycle of the fragment. – me_ Oct 23, 2018 at 5:57.

How to load a Fragment in an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

How many ways to call Fragment?

There are 12 lifecycle methods for fragment.


1 Answers

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
}
like image 188
ssawchenko Avatar answered Sep 19 '22 21:09

ssawchenko