안드로이드

[Android] Fragment commit commitNow 차이

코딩하는후운 2022. 11. 4. 16:06
반응형

Fragment commit vs commitNow

 

commitNow()

동기적으로 트랜잭션 처리.

// Activity.kt
log("Transaction: begin")
supportFragmentManager
        .beginTransaction()
        .replace(R.id.layout, Fragment2())
        .commitNow()
log("Transaction: end")

// Logcat
Transaction: begin
Fragment2: onAttach
Fragment2: onCreate
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment2: onCreateView
Fragment2: onViewCreated
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume
Transaction: end
Fragment1: onDestroy
Fragment1: onDetach



commitNow()가 끝난 시점에서 Fragment의 교체가 완료되어 있는것을 알수 있다.


또한 Activity의 onCreate() commitNow()를 부를 경우는

// Logcat
Transaction: begin
Fragment2: onAttach
Fragment2: onCreate
Fragment1: onDestroy
Fragment1: onDetach
Transaction: end
Fragment2: onCreateView
Fragment2: onViewCreated
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume



Activity측의 준비가 끝날 때까지는 View의 생성 및 추가할 수 없기 때문에, onCreate() 이후로 미뤄주는것 같다.
어쨋든 commitNow()가 끝난 시점에서 적어도 onAttach()와 onCreate()까지 완료되어 있는지 알 수 있습니다.

commit()이라면

// Logcat
Transaction: begin
Transaction: end
Fragment2: onAttach
Fragment2: onCreate
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment2: onCreateView
Fragment2: onViewCreated
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume
Fragment1: onDestroy
Fragment1: onDetach


Handler에 post해서 처리를 뒤로 미뤘기 때문에 당연하네요.

주의해야 할 점

commit()과 같이 사용하지 않는 것이 좋을듯 합니다.
동기적으로 처리하는 commitNow()에 대해서 commit()은 Handler에 처리를 post하므로 2개를 연속적으로 사용한 경우에
순서대로 처리되지 않는 문제가 발생합니다.

commitNow()는 BackStack은 사용할 수 없다고 합니다.

 

 

참조 :

https://pluu.github.io/blog/android/2017/01/26/fragmentTransaction/

 

Pluu Dev - [번역] FragmentTransaction에 새롭게 추가된 commitNow()에 대해

[메모] Gradle의 Version Category를 사용하여 Extra Properties 호환성 유지 Posted on 25 Sep 2022 [메모] 앱의 Version Code 변경 Posted on 17 Sep 2022 [삽질] 버튼의 클릭 터치 영역 커스텀 해보기 Posted on 04 Sep 2022 Lint 작

pluu.github.io

 

반응형