Home > Mobile >  when is onAttach invoked?
when is onAttach invoked?

Time:08-04

The android documentation says that The onAttach() callback is invoked when the fragment has been added to a FragmentManager and is attached to its host activity.

A piece of my code in the activity:

...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment  = fm.findFragmentById(R.id.fragment_container);
        if(fragment == null){
            fragment = new CrimeFragment();
            fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
        }

        Log.d(MAIN_ACTIVITY_LOG_TAG, "onCreate(Bundle)");
    }
...

A piece of my code in the fragment:

...
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(CRIME_FRAGMENT_LOG_TAG, "onAttach(Context)");
    }
...

The log:

...
2022-08-03 12:36:42.512 26035-26035/com.bignerdranch.android.criminalintent D/main_activity_log_tag: onCreate(Bundle)
2022-08-03 12:36:42.514 26035-26035/com.bignerdranch.android.criminalintent D/crime_fragment_log_tag: onAttach(Context)
...

As you can see onAttach() isn't invoked when the fragment is added to the FragmentManager.

So when actually is onAttach() invoked?

CodePudding user response:

Fragment transactions are asynchronous by default. They are not executed immediately but just scheduled for execution at a later point.

If you want to make your fragment transaction synchronous, change commit() to commitNow(). Most of the cases you don't really need that.

  • Related