Search code examples
androidandroid-fragmentsfragment-lifecycle

Does onCreate() called after commit()?


  private class DrawerItemClickListener implements ListView.OnItemClickListener {

       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
           selectItem(position);

       }
   }

private void selectItem(int position) {
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);

        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);

        mDrawerTitle=mPlanetTitles[position];
        mDrawerLayout.closeDrawers();


    }

My app is the a demo with a drawer.The eight planet drawernavigation demo.When you click a item of the ListView shows on the drawer,the planet picture on the fragment changes.

Here is my confusion:

I think the onCreate and onCreateView method of Fragment will called subsequence to "fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();".

But actually,They called after onItemClick() finished. Why? Thanks in advance.


Solution

  • If you read the documentation of the commit method it says:

    Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

    Since selectItem is also on the main thread, the commit won't happen until after selectItem returns (but not necessarily right after!).