Sobes.tech
Junior

How to pass data from one fragment to another?

sobes.tech AI

Answer from AI

  1. Bundle Arguments: Used for passing primitive data types and objects implementing Parcelable or Serializable when creating a new fragment instance.

    // In the sending fragment
    val bundle = Bundle().apply {
        putString("key", "value")
    }
    val fragment = TargetFragment().apply {
        arguments = bundle
    }
    
    // In the receiving fragment
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val value = arguments?.getString("key")
        // ... use of value
    }
    
  2. Shared ViewModel: Fragments belonging to the same Activity can use a shared ViewModel to exchange data.

    // SharedViewModel
    class SharedViewModel : ViewModel() {
        val data = MutableLiveData<String>()
    }
    
    // In the sending fragment
    private val sharedViewModel: SharedViewModel by activityViewModels()
    sharedViewModel.data.value = "value"
    
    // In the receiving fragment
    private val sharedViewModel: SharedViewModel by activityViewModels()
    sharedViewModel.data.observe(viewLifecycleOwner) { value ->
        // ... use of value
    }
    
  3. Using interface callback: One fragment calls a method in the Activity, and the Activity then calls a method in another fragment.

    // Interface in Activity or a separate file
    interface DataTransferListener {
        fun onDataReceived(data: String)
    }
    
    // In the sending fragment
    (activity as? DataTransferListener)?.onDataReceived("value")
    
    // In the Activity implementing the interface
    override fun onDataReceived(data: String) {
        val targetFragment = supportFragmentManager.findFragmentById(R.id.target_fragment_container) as? TargetFragment
        targetFragment?.updateUI(data)
    }
    
    // In the receiving fragment
    fun updateUI(data: String) {
        // ... update UI with data
    }
    
  4. Fragment Result API: The modern and recommended way for exchanging data between fragments.

    // In the sending fragment (set the result)
    setFragmentResult("requestKey", bundleOf("bundleKey" to "value"))
    
    // In the receiving fragment (listen for the result)
    setFragmentResultListener("requestKey") { requestKey, bundle ->
        val result = bundle.getString("bundleKey")
        // ... use of result
    }