Android

[안드로이드] Fragment Lifecycle (프래그먼트 생명 주기)

베르_최성훈 2023. 5. 30. 22:56

Fragment 인스턴스는 자체 생명 주기를 갖는다! 사용자가 앱을 탐색하고 상호 작용할 때 프래그먼트는 add, remove, 되고 화면으로 들어가거나 나갈 때 수명 주기가 전환된다.

 

생명 주기를 관리하기 위해 Fragment 는 LifecycleOwner 를 구현한다. 이 오브젝트를 통해 getLifecycle() 메서드로 접근 가능하다.

Fragment 생명 주기 은 다음과 같이 enum 으로 구성된다.

 

1. INITIALIZED 

2. CREATED

3. STARTED

4. RESUMED

5. DESTROYED

 

Fragment 생명주기 콜백함수와 Fragment 생명주기는 다르다.

 

 

1. onAttach()onDetach()

프래그먼트가 인스턴스화 되면 INITIALIZED 상태에서 시작.

프래그먼트가 트랜잭션을 사용해서 다른 Lifecycle 로 전환하려면 FragmentManager 에 추가해야한다. 

 

프래그먼트가 FragmentManager 에 added() 되면 host Activity 에 attached 된다. fragment 가 활성화되면 FragmentManager Lifecycle state 를 관리한다. 또한 더 이상 사용하지 않으면 detach 하는 일도 한다. 이때 findFragmentById() 는 프래그먼트를 반환한다.

  • onAttach() : Fragment 가 FragmentManager 에 추가되고 host Activity 에 Attached 된 상태에서 모든 Lifecycle state 가 변경되기 전에 호출된다.
  • onDetach() :  Fragment 가 FragmentManager 에 추가되고 host Activity 에 Detached 된 상태에서 모든 Lifecycle state 가 변경된 후에 호출된다.

* FragmentTransaction 의 attach(), detach() 와는 관계 없다.

* FragmentManager 에서 지워진 Fragment 를 재사용하지 마라.

 

2.  Fragment CREATED

FragmentCREATD 되면 FragmentManager  에 add 되고 onAttach() 콜백

뷰가 아직 생성되지 않았으며 뷰와 관련 없는 Fragment 자체와 관련된 SavedStateRegistry 를 저장하는데 적합하다.

 

view 와 관련된 state 는 절대 restore 하면 안됨을 명심!

 

이 트랜잭션은 onCreate() 콜백을 호출한다. savedInstanceState Bundle 을 가진다.

프래그먼트가 처음 생성되면 savedInstanceState 는 null 이다. recreation 되면 항상 Null 은 아닐 수 있다.

 

3.  Fragment CREATED and View INITIALIZED

view Lifecycle 은 Fragment 가 유효한 View instance 를 제공했을 때 생성된다. LayoutId 로 적절한 시간에 View 를 그린다. onCreateView 를 override 해서 view를 inflate 하거나 create 할 수 있다.

 

FragmentView 의 인스턴스가 null 이 아니면 getViewLifeCycleOwnerLiveData() 가 새로 초기화된 LifecycleOwner 로 업데이트 되고 onViewCreated 가 불리게 된다.

 

4.  Fragment CREATED and View CREATED

view 가 created 되었다면 FragmentLifeCycle 은 CREATED 상태가 된다. Fragment View와 관련된 추가적인 restore 을 진행하고 onViewStateRestored() 콜백을 호출한다.

 

5.  Fragment STARTED and View STARTED

Lifecycle-aware component 는 STARTED 상태에 종속시켜라.

https://developer.android.com/topic/libraries/architecture/lifecycle

 

수명 주기 인식 구성요소로 수명 주기 처리  |  Android 개발자  |  Android Developers

새 Lifecycle 클래스를 사용하여 활동 및 프래그먼트 수명 주기를 관리합니다.

developer.android.com

child Fragment manager 에 FragmentTransaction 을 수행하는 것은 STARTED 에서 수행해야 한다.

Fragement's Lifecycle 이 STARTED 되면 fragment's view Lifecycle 도 바로 STARTED 된다.이 상태가 되면 onStart() 가 호출된다.

 

6.  Fragment RESUMED and View RESUMED

Fragment 가 보이기 시작하면 사용자와 상호작용할 준비가 되었다. Fragement's Lifecycle 이 RESUMED 상태가 된다.

RESUMED 되지 않은 Fragment 를 억지로 조작하거나 보이게 하려고 해선 안된다.

 

7.  Fragment STARTED and View STARTED

사용자가 fragment 를 떠났지만 여전히 보이고 있다면 STARTED 상태가 되고 onPause() 콜백이 호출된다.

 

8.  Fragment CREATED and View CREATED

더 이상 보이지 않으면 CREATED 상태가 된다. 이 transition 은 부모 액티비티나 프래그먼트가 stopped 되었을 때 뿐만 아니라 액티비티나 프래그먼트의 상태가 저장될 때도 트리거 된다. state 가 save 되기 전에 ON_STOP 이 호출됨을 보장한다. (API 28+)

 

9.  Fragment CREATED and View DESTROYED 

모든 animations and transitions exit 이 완전히 되면 프래그먼트 view 는 detached 된다. 그럼 view LifeCycle 은 detached 되고 onDestroyView() 콜백을 호출한다. 이때 view Lifecycle 은 끝이나고 getViewLifeCycleOwnerLiveData() 는 null 이 된다. 이때 fragment's view 는 remove 되야한다. fragment's view 를 garbage collecting 하도록 허용한다.

 

10.  Fragment DESTROYED 

fragment 가 removed 되거나 fragmentManager 가 파괴되면 Fragment's Lifecycle 이 DESTROYED 된다. onDestroy() 를 호출하고 fragment 생명 주기는 끝이 난다.

 

https://developer.android.com/guide/fragments/lifecycle

 

Fragment lifecycle  |  Android Developers

Fragment lifecycle Stay organized with collections Save and categorize content based on your preferences. Each Fragment instance has its own lifecycle. When a user navigates and interacts with your app, your fragments transition through various states in t

developer.android.com