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.
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.
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.
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.
There are 12 lifecycle methods for fragment.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With