안드로이드

프래그먼트 간 데이터 전달 (Fragment Result API)

ddayunee 2022. 3. 6. 11:09
반응형

프래그먼트간 데이터 전달 방법엔 여러가지 방법이 있습니다.

1. bundle과 FragmentManager로 전달
2. Fragment Result API를 이용하여 전달
3. Fragment간 shared ViewModel로 전달
4. Jetpack의 Navigation 에서 제공하는 safe-args로 전달

오늘은 Fragment Result API를 이용하여 전달하는 방법에 대하여 기술하겠습니다.

해당 API를 사용하기 위해서는 build.gradle에 아래와 같이 설정합니다.

dependencies {
    def fragment_version = "1.4.1" //1.3.0-alpha04 이상
    
   
    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
}

FragmentManager은 프래그먼트의 결과의 중앙 저장소 역할을 하기 때문에 프래그먼트가 서로 직접 참조할 필요없이 프래그먼트간의 통신을 할 수 있습니다.

 

위 그림과 같은 관계의 FragmentA 와 FragmentB 사이의 데이터 공유를 위해서는 아래 코드처럼 적용하여 사용할 수 있습니다.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // Use the Kotlin extension in the fragment-ktx artifact
    setResultListener("requestKey") { key, bundle ->
        // We use a String here, but any type that can be put in a Bundle is supported
        val result = bundle.getString("bundleKey")
        // Do something with the result...
    }
}

데이터를 받아오는 쪽의 코드입니다.

button.setOnClickListener {
    val result = "result"
    // Use the Kotlin extension in the fragment-ktx artifact
    setResult("requestKey", bundleOf("bundleKey" to result))
}

데이터를 발생시키는 쪽의 코드입니다.

- 백 스택에 있는 프래그먼트는 STARTED 상태가 될 때까지 result를 받지않습니다.
- 수신하는 프래그먼트가 STARTED 상태면 리스너의 콜백이 바로 실행됩니다.

 

Parent Fragment - Child Fragment

 

위 그림처럼 Parent Fragment와 Child Fragment 사이에 데이터 공유가 필요할 때는 parentFragmentManager() 혹은 childFragmentManager()를 이용하면 됩니다.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // We set the listener on the child fragmentManager
    childFragmentManager.setResultListener("requestKey") { key, bundle ->
        val result = bundle.getString("bundleKey")
        // Do something with the result..
    }
}
button.setOnClickListener {
    val result = "result"
    // Use the Kotlin extension in the fragment-ktx artifact
    setResult("requestKey", bundleOf("bundleKey" to result))
}

 

참고 사이트 : 

https://developer.android.com/training/basics/fragments/pass-data-between?hl=ko 

 

프래그먼트 간 데이터 전달  |  Android 개발자  |  Android Developers

프래그먼트 간 데이터 전달 프래그먼트 1.3.0-alpha04부터 각 FragmentManager는 FragmentResultOwner를 구현합니다. 즉, FragmentManager는 프래그먼트 결과의 중앙 저장소 역할을 할 수 있습니다. 이번 변경을 통

developer.android.com

https://velog.io/@sysout-achieve/Android-Fragment%EA%B0%84-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%A0%84%EB%8B%AC-%EB%B0%A9%EB%B2%95%EB%93%A4

 

반응형