Search code examples
androidandroid-fragmentsandroid-activityandroid-fragmentactivityandroid-lifecycle

Common methods to both Activitiy and Fragment in Android


I am little skeptical about the common life cycle methods to Activity and Fragment. I got a question in an interview and now i am confused about the question.

Here was the exact question asked Which of the following lifecycle methods are common to Activity and Fragment?

onAttach(), onCreate(), onStart or onDetach ?

A bit explanation would be helpful.


Solution

  • Common methods to both activity and fragment here are onCreate() & onStart()

    Common meaning that both fragment and activity have onCreate() and onStart() [Also onResume(), onPause(), onStop() & onDestroy()] life cycle methods.

    It does not mean that if you have a fragment in an activity then the onCreate() or onStart() method are the same for both activity and the considered fragment. They are separate methods, one running for the activity (for activity life cycle) and one running for fragment (for fragment life cycle)

    onAttach() and onDetach() callbacks are specific to fragments only.

    onAttach() is called when the fragment has been associated with the activity (the Activity is passed in here).

    onDetach() is called when the fragment is being disassociated from the activity.

    From android developers documentation,

    if you're converting an existing Android application to use fragments, you might simply move code from your activity's callback methods into the respective callback methods of your fragment.

    References: https://developer.android.com/guide/components/fragments https://developer.android.com/reference/android/app/Activity