Sobes.tech
Junior — Middle

What methods are used to pass data when returning from one fragment to another in mobile applications?

sobes.tech AI

Answer from AI

The following methods are usually used for data transfer when returning from one fragment to another in Android:

  1. Callback interfaces — the sending fragment defines an interface that the receiving fragment or activity implements, and through it, data is passed.

  2. Shared ViewModel — if MVVM architecture is used, both fragments can share a ViewModel, where data is updated and observed.

  3. setFragmentResultListener and setFragmentResult — modern APIs from androidx.fragment for passing data between fragments without needing to directly interact with each other.

Example using setFragmentResult:

// In the sending fragment
val result = Bundle()
result.putString("key", "value")
parentFragmentManager.setFragmentResult("requestKey", result)

// In the receiving fragment
parentFragmentManager.setFragmentResultListener("requestKey", this) { key, bundle ->
    val value = bundle.getString("key")
    // handle data
}
What methods are used to pass data when returning… - sobes.tech