Android Fragment to Fragment 데이터 전달

푸른하늘·2022년 6월 26일
0
post-thumbnail

🍎<구성도>

🍎CASE BY CASE

  1. Basic 하게 Bundle 에 담아서 데이터를 전달
  2. Fragment Reslut API를 통해서 데이터 전달
  3. ViewModel를 사용하여 데이터를 공유
  4. Jetpack Navigation을 활용하여 safe-args로 전달

🍏 Basic Bundle 데이터 전달

이건 코드에 없음 너무 간단해서

FragmentA (Giver)

val bundle = Bundle()
bundle.putString("key", "value")

val fragmentB = FragmentB()
fragmentB.setArgument(bundle)

parentFragmentManager.beginTransaction()
	.replace(R.id.frameconainer ,fragmentB);
    transaction.commit()

FragmentB (Receiver)

	val result= arguments?.getString("key") // result == "value"

🍏 Fragment Reslut API를 통해서 데이터 전달

FragmentA (Giver)

setFragmentResultListener("requestKey"){ requestkey, bunlde ->
		val result = bunlde.getString("value")
        binding.fragmentAtextView.text = result
}

FragmentB (Receiver)

 val result = binding.fragmentBTextView.text.toString()
    // Use the Kotlin extension in the fragment-ktx artifact
    setFragmentResult("requestKey", bundleOf("value" to result))

🍏ViewModel를 사용하여 데이터를 공유

Activity 생성

class MainActivity : AppCompatActivity() {

    private val viewModel: MainActivityViewModel by viewModels()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.selectedItem.observe(this, Observer { item ->
            // Perform an action with the latest item data
        })
    }
}

Activity ViewModel 생성

class MainActivitiyViewModel : ViewModel() {
    private val _fragmentTextValue = MutableLiveData<String>()
    
    val fragmentTextValue: LiveData<String> 
    	get() = _fragmentTextValue

    fun updateItem(text :String) {
       _fragmentTextValue.value = _fragmentTextValue.value?.text.toString()
    }
}

Fragment A & Fragment B 생성

class FragmentA : Fragment(){
	private lateinit var binding: FragmentABinding
    private val viewModel: MainActivitiyViewModel by activityViewModels()
	
    override fun onCreateView(
    //생략 ):
    
     binding.lifecycleOwner = this
     binding.fragmentAtextView.text= viewModel.fragmentTextValue.toString()
     
     binding.button.setOnClickListener{
     	viewModel.updateItem("전달한다 받아라 fragemntB야")
     }
     
     
     
     
        

}
class FragmentB : Fragment(){
    private val viewModel: MainActivitiyViewModel by activityViewModels()
    
    override fun onCreateView(
    //생략 ):
    
	 binding.lifecycleOwner = this
     binding.fragmentBtextView.text= viewModel.fragmentTextValue.toString()
}

🍏 Jetpack Navigation을 활용하여 safe-args로 전달

  • Jetpack compose Navigation 세팅
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_graph"
    app:startDestination="@id/fragmentA">

    <fragment
        android:id="@+id/fragmentA"
        android:name="com.gunt.fragmentdatapassexample.pass.passargs.fragmentA"
        android:label="fragmentA" >
        <action
            android:id="@+id/fragmentAToB"
            app:destination="@id/fragmentB"
            app:launchSingleTop="true" />
        <argument
            android:name="argsString"
            app:argType="string"
            android:defaultValue=""/>
    </fragment>
    <fragment
        android:id="@+id/fragmentB"
        android:name="com.gunt.fragmentdatapassexample.pass.passargs.fragmentB"
        android:label="fragmentB" >
        <action
            android:id="@+id/passBToA"
            app:destination="@id/fragmentA"
            app:launchSingleTop="true"
            app:popUpTo="@id/nav_graph" />
        <argument
            android:name="argsString"
            app:argType="string"
            android:defaultValue=""/>
    </fragment>
</navigation>

FragmentA

class FragmentA : Fragment(){
 override fun onCreateView(
    //생략 ):
    
     val args: navFragmentA by navArgs()
        binding.textView.text = args.argsString // nav agrument 생성한것

        binding.btnSend.setOnClickListener {
            val action = FragmentADirections.passAToB(binding.etText.text.toString())
            findNavController().navigate(action)
        }
}

FragmentB

class FragmentA : Fragment(){
 override fun onCreateView(
    //생략 ):
    
     val args: navFragmentB by navArgs()
        binding.textView.text = args.argsString // nav agrument 생성한것

        binding.btnSend.setOnClickListener {
            val action = FragmentADirections.passBToA(binding.etText.text.toString())
            findNavController().navigate(action)
        }
}

참고자료

profile
Developer-Android-CK

0개의 댓글