Let\'s say that we have two fragments: MainFragment and SelectionFragment. The second one is build for selecting some object, e.g. an integer. Ther
Since Fragment KTX 1.3.0-alpha04 Android supports passing data between fragments or between fragments and activities. It's similar to startActivityForResult logic.
Here is an example with Navigation Component. You can read more about it here
build.gradle
implementation "androidx.fragment:fragment-ktx:1.3.0-alpha04"
FragmentA.kt
class FragmentA : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Step 1. Listen for fragment results
setFragmentResultListener(FragmentB.REQUEST_KEY) { key, bundle ->
// read from the bundle
}
// Step 2. Navigate to Fragment B
findNavController().navigate(R.id.fragmentB)
}
}
FragmentB.kt
class FragmentB : Fragment() {
companion object {
val REQUEST_KEY = "FragmentB_REQUEST_KEY"
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
buttonA.setOnClickListener { view ->
// Step 3. Set a result
setFragmentResult(REQUEST_KEY, bundleOf("data" to "button clicked"))
// Step 4. Go back to Fragment A
findNavController().navigateUp()
}
}
}