fragment add vs replace (with remove, addToBackStack)

나고수·2022년 5월 22일
0

1일1공부

목록 보기
45/67

add

 fun addFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .add(R.id.container, fragment)
            .addToBackStack(fragment.javaClass.simpleName)
            .commit()
    }

Fragment A -> Fragment B

add는 onAttach() ~ onResume()까지만 lifecycle이 진행됨
A가 onResume()인 상태에서 B가 onAttach()됨

Fragment B -> 백버튼

Fragment B 는 onPause() ~ onDetach() 됨
Fragment A 는 여전히 onResume() 상태임 👈 A가 보임

  • 만약 addToBackStack(null)을 하지 않는다면?
    스택에 쌓이지 않아 A, B 모두 onDetach() 되며 activity 자체가 onDestroy() 됩니다.
    fun removeFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .remove(fragment)
            .addToBackStack(fragment.javaClass.simpleName)
            .commit()
    }

Fragment A -> Fragment B -> remove B -> 백버튼

remove B 의 결과 --> B의 onDestroyView()
백버튼의 결과 --> B의 OnCreateView() 👈 B가 다시 보여집니다!!

  • 만약 remove()를 addToBackStack()을 하지 않으면?
    remove B 의 결과 --> B의 onDestroyView()
    백버튼의 결과 --> B의 detach() A의 resume() 👈 A가 보여집니다!!

replace

 fun replaceFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, fragment)
            .addToBackStack(fragment.javaClass.simpleName)
            .commit()
    }

Fragment A -> Fragment B

A가 onDestroyView()인 상태에서 B가 onAttach()됨
//백스택에 A가 있었다는게 저장되어야하기 때문에 onDestroy()로 fragment를 아예 없애버리는게 아니라 onDestroyView()까지만 진행되는듯.

  • 만약 addToBackStack(null)을 하지 않는다면?
    onDestroy()까지 모든 라이프사이클이 진행됨
    A가 onDestroy()인 상태에서 B가 onAttach()됨

Fragment A -> Fragment B -> 백버튼

Fragment A -> Fragment B 로 갈때 : A는 onDestroyView() 상태
백버튼 눌렀을 때 : B는 onDetach()가 되며, A는 onCreateVew()가 됨

  • 만약 addToBackStack(null)을 하지 않는다면?
    스택에 쌓이지 않아 A, B 모두 onDetach() 되며 activity 자체가 onDestroy() 됩니다.
    fun removeFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .remove(fragment)
            .addToBackStack(fragment.javaClass.simpleName)
            .commit()
    }

Fragment A -> Fragment B -> remove B -> 백버튼

remove B 의 결과 --> B의 onDestroyView()
백버튼의 결과 --> B의 OnCreateView() 👈 B가 다시 보여집니다!!
여기서 백버튼을 한번 더 누르면, B가 onDetach()되고, A는 onCreateView()가 됩니다.

  • 만약 remove()를 addBackStack() 하지 않으면?
    remove B 의 결과 --> B의 onDestroyView()
    백버튼의 결과 --> B의 onDetach() , A의 onCreateView() 👈 A가 보여짐
    여기서 백버튼을 한번 더 누르면, A가 onDetach()됩니다.

정리 😎

  • add() 👉 onAttach() ~ onResume() 까지의 라이프사이클을 돈다. 기존 프래그먼트 위에 쌓는 느낌.
  • replace() 👉 onAttach() ~ onDestroy() 까지의 라이프사이클을 돈다. 기존 프래그먼트를 없애고 새로운 프래그먼트로 대체하는 느낌.
  • remove() 👉 존재하는 프래그먼트를 제거.
  • addToBackStack() 👉 beginTransition() ~ commit() 까지의 상태를 저장.
  • navigation은 fragment A에서 fragment B 로 갈때
    A의 onDestroyView()까지만 찍히는 것으로보아
    addToBackStack()을 넣은 replace() 같다.
profile
되고싶다

0개의 댓글