[Android]/학습

[Android/Kotlin] Activity와 Fragment

Cocoa's Story 2022. 10. 26. 11:25

 

작업 및 백 스택 이해  |  Android 개발자  |  Android Developers

일반적으로 앱에는 여러 활동이 포함됩니다. 각 활동은 사용자가 실행할 수 있는 특정 종류의 작업을 중심으로 설계되어야 하며 다른 활동을 시작할 수 있어야 합니다. 예를 들어 이메일 앱에는

developer.android.com

 안드로이드 앱에서 뒤로가기를 눌렀을 때.. 제대로 이전 화면이 종료되지 않고 겹겹이 쌓여있던 걸 경험한 적이 있다. Activity와 Fragment의 특성을 제대로 고려해주지 않았기 때문에 발생한 문제였다고 생각한다.

 

 activityA -> activityB 화면 전환의 경우 액티비티가 "대체"되지만,

 fragmentA -> fragmentB 화면 전환의 경우 액티비티 위에 프레그먼트를 겹겹이 쌓아올리는 것이 가능하다.

 

 

 

 

이전 레이아웃에 프래그먼트를 추가

supportFragmentManager.beginTransaction()
                        .add(R.id.fragment_container, firstFragment).commit()

 

 

한 프래그먼트를 다른 프래그먼트로 교체

 프래그먼트 교체 절차는 프래그먼트 추가 절차와 비슷하지만, add() 대신 replace() 메서드를 사용해야 한다.

프래그먼트 교체/삭제와 같은 Fragment Transaction을 실행할 때는 사용자가 뒤로 이동하여 변경을 '실행취소'하도록 허용하는 것이 적절한 경우가 많다. FragmentTransaction을 통해 사용자가 뒤로 이동할 수 있게 하려면, FragmentTransaction을 커밋하기 전에 addToBackStack()을 호출해야 한다.

// Create fragment and give it an argument specifying the article it should show
    val newFragment = ArticleFragment()
    Bundle args = Bundle()
    args.putInt(ArticleFragment.ARG_POSITION, position)
    newFragment.arguments = args

    val transaction = supportFragmentManager.beginTransaction().apply {
      // Replace whatever is in the fragment_container view with this fragment,
      // and add the transaction to the back stack so the user can navigate back
      replace(R.id.fragment_container, newFragment)
      addToBackStack(null)
    }

    // Commit the transaction
    transaction.commit();