Fragments lifecycle
Significa que el fragmento no es destruido, solo es quitado de la antigua actividad (detached) y puesto en la nueva actividad (attached) .
Retiene la instancia cada que el sistema resetea por automático la actividad (por ejemplo se rota la pantalla).
Cuando se utiliza setRetainInstance(true)
y sólo se maneja la creación de una instancia del fragmento, sólo será invocado una vez onCreate
y onDestroy
.
Cómo afecta setRetainInstance al ciclo de vida de los fragmentos
Inicia la actividad (sin agregar ningun fragmento)
ACTIVITY::ON_CREATE, bundle=null
ACTIVITY->SET_CONTENT_VIEW
ACTIVITY->END_ON_CREATE
ACTIVITY:ON_START
ACTIVITY:ON_RESUME
Se presiona un botón que agrega un fragment
->FRAGMENT:CONSTRUCTOR
FRAGMENT:ON_ATTACH
FRAGMENT:ON_CREATE
FRAGMENT:ON_CREATE_VIEW
FRAGMENT:ON_ACTIVITY_CREATED
FRAGMENT:ON_START
FRAGMENT:ON_RESUME
Se rota la actividad (con el fragmento agregado)
ACTIVITY:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_PAUSE
ACTIVITY:ON_PAUSE
FRAGMENT:ON_STOP
ACTIVITY:ON_STOP
FRAGMENT:ON_DESTROY_VIEW
FRAGMENT:ON_DETACH
ACTIVITY:ON_DESTROY
ACTIVITY::ON_CREATE, bundle=Bundle[@41704bd8]
FRAGMENT:ON_ATTACH
ACTIVITY->SET_CONTENT_VIEW
ACTIVITY->END_ON_CREATE
FRAGMENT:ON_CREATE_VIEW
FRAGMENT:ON_ACTIVITY_CREATED
ACTIVITY:ON_START
FRAGMENT:ON_START
ACTIVITY:ON_RESUME
FRAGMENT:ON_RESUME
Se presiona un botón para remover el fragmento
FRAGMENT:ON_PAUSE
FRAGMENT:ON_STOP
FRAGMENT:ON_DESTROY_VIEW
FRAGMENT:ON_DESTROY
FRAGMENT:ON_DETACH
Se presiona botón home, (el fragmento se encuentra agregado)
ACTIVITY:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_PAUSE
ACTIVITY:ON_PAUSE
FRAGMENT:ON_STOP
ACTIVITY:ON_STOP
Se simula que android mata el proceso por falta de memoria (con el fragmento agregado)
ACTIVITY:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_PAUSE
ACTIVITY:ON_PAUSE
FRAGMENT:ON_STOP (podria no ejecutarse)
ACTIVITY:ON_STOP (podria no ejecutarse)
Process 3804 exited cleanly (1)
ACTIVITY::ON_CREATE, bundle=Bundle[mParcelledData.dataSize=1084]
->FRAGMENT:CONSTRUCTOR
FRAGMENT:ON_ATTACH
FRAGMENT:ON_CREATE
ACTIVITY->SET_CONTENT_VIEW
ACTIVITY->END_ON_CREATE
FRAGMENT:ON_CREATE_VIEW
FRAGMENT:ON_ACTIVITY_CREATED
ACTIVITY:ON_START
FRAGMENT:ON_START
ACTIVITY:ON_RESUME
FRAGMENT:ON_RESUME
TODO: WITH FINISH ACTIVITY, AGREGAR ONATTACHFRAGMENT, AGREGAR SI ESTÁN CONSTRUIDOS LOS BUNDLES QUE SE ENVÍAN EN LOS MÉTODOS DE LOS FRAGMENTOS.
TODO: CREAR LIFECYCLE DE LOS DIALOGFRAGMENTS.
Inicia la actividad (sin agregar ningun fragmento)
ACTIVITY:ON_CREATE, bundle=null
ACTIVITY->SET_CONTENT_VIEW
ACTIVITY->END_ON_CREATE
ACTIVITY:ON_START
ACTIVITY:ON_RESUME
Se presiona un botón que agrega un fragment
->FRAGMENT:CONSTRUCTOR
FRAGMENT:ON_ATTACH
FRAGMENT:ON_CREATE
FRAGMENT:ON_CREATE_VIEW
FRAGMENT:ON_ACTIVITY_CREATED
FRAGMENT:ON_START
FRAGMENT:ON_RESUME
Se rota la actividad (con el fragmento agregado)
ACTIVITY:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_PAUSE
ACTIVITY:ON_PAUSE
FRAGMENT:ON_STOP
ACTIVITY:ON_STOP
FRAGMENT:ON_DESTROY_VIEW
FRAGMENT:ON_DESTROY
FRAGMENT:ON_DETACH
ACTIVITY:ON_DESTROY
ACTIVITY::ON_CREATE, bundle=Bundle[@417023c8]
->FRAGMENT:CONSTRUCTOR
FRAGMENT:ON_ATTACH
FRAGMENT:ON_CREATE
ACTIVITY->SET_CONTENT_VIEW
ACTIVITY->END_ON_CREATE
FRAGMENT:ON_CREATE_VIEW
FRAGMENT:ON_ACTIVITY_CREATED
ACTIVITY:ON_START
FRAGMENT:ON_START
ACTIVITY:ON_RESUME
FRAGMENT:ON_RESUME
Se presiona un botón para remover el fragmento
FRAGMENT:ON_PAUSE
FRAGMENT:ON_STOP
FRAGMENT:ON_DESTROY_VIEW
FRAGMENT:ON_DESTROY
FRAGMENT:ON_DETACH
Se presiona botón home, (el fragmento se encuentra agregado)
ACTIVITY:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_PAUSE
ACTIVITY:ON_PAUSE
FRAGMENT:ON_STOP
ACTIVITY:ON_STOP
Se simula que android mata el proceso por falta de memoria (con el fragmento agregado)
ACTIVITY:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_SAVE_INSTANCE_STATE
FRAGMENT:ON_PAUSE
ACTIVITY:ON_PAUSE
FRAGMENT:ON_STOP (podria no ejecutarse)
ACTIVITY:ON_STOP (podria no ejecutarse)
Process 3642 exited cleanly (1)
ACTIVITY::ON_CREATE, bundle=Bundle[mParcelledData]
->FRAGMENT:CONSTRUCTOR
FRAGMENT:ON_ATTACH
FRAGMENT:ON_CREATE
ACTIVITY->SET_CONTENT_VIEW
ACTIVITY->END_ON_CREATE
FRAGMENT:ON_CREATE_VIEW
FRAGMENT:ON_ACTIVITY_CREATED
ACTIVITY:ON_START
FRAGMENT:ON_START
ACTIVITY:ON_RESUME
FRAGMENT:ON_RESUME
Se puede obtener a través de getActivity()
pero debe tener cuidado ya que retorna null cuando el fragmento no se encuentra atado (attached
) a la actividad.
Siempre que es reseteada la actividad, se invoca el método fragment.onAttach
para notificar al fragmento la nueva instancia de la actividad.
Cuando la actividad quita y agrega automáticamente los fragmentos que tenía contenidos (se resetea la actividad), la actividad está disponible en todos los métodos del fragmento a través del método getActivity()
, sin embargo en los métodos onAttach,onCreate,onCreateView
la actividad ya fue creada pero aún no ha sido cargada su vista (no se ha ejecutado activity.onCreate()
).
activity-state->fragment-callbacks
Nota: Cuando se resetea una actividad, POR AUTOMÁTICO quita y vuelve a agregar todos los fragmentos que tenía agregados.
onAttach: El fragment se ha adjuntado al Activity, android pasará una referencia hacia la nueva actividad creada cada que haya un cambio de configuración.
onCreate
Este método se ejecuta cuando es creado el fragmento. Un fragmento se considera que es creado cuando se agrega a la actividad, el fragmento se puede agregar a la actividad de 2 formas:
Manual: Se agrega programáticamente el fragmento a la actividad (a través de una tx).
Automática: Cuando android resetea la actividad, resetea el fragmento, es decir lo destruye y lo vuelve a agregar (Android requiere un constructor default del fragmento para crear la instancia y agregarla).
Cuando el fragmento retiene su instancia setRetainInstance(true)
quiere decir que no es reseteado aunque se resetee la actividad y no hay reseteos automáticos (se crea y se destruye), por lo tanto onCreate
sólo es invocado cuando se agrega el fragmento a la actividad de manera manual.
Las mismas reglas de este método aplican para fragment.onDestroy()
Utilice este método para inicializar todos los objetos del fragmento que no sean vistas.
onCreateView: Aquí se crea y retorna la vista del fragmento. Se invoca siempre que se resetea la actividad, aún cuando se retiene la instancia del fragmento.
onActivityCreated(Bundle): Le dice al fragmento que su actividad ha sido completamente creada, es decir se terminó de invocar Activity.onCreate()
y ya se encuentra cargada toda la vista de la actividad.
onViewStateRestored(Bundle)
: tells the fragment that all of the saved state of its view hierarchy has been restored.
onStart()
: makes the fragment visible to the user (based on its containing activity being started).
onResume()
: makes the fragment interacting with the user (based on its containing activity being resumed).
As a fragment is no longer being used, it goes through a reverse series of callbacks:
onPause()
: fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
onStop()
: fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
onDestroyView()
: allows the fragment to clean up resources associated with its View.
onDestroy()
: called to do final cleanup of the fragment's state.
onDetach()
: called immediately prior to the fragment no longer being associated with its activity.
La principal diferencia en el ciclo de vida es que las actividades son introducidas automáticamente por el sistema al backstack, mientras que los fragmentos deben ser introducidos manualmente al backstack.
Al igual que una actividad:
Al igual que las actividades, un fragmento puede ser destruido por lo que puede utilizar el método onSaveInstanceState()
y recuperarlo en onCreate()
,onCreateView()
,onActivityCreated()