I just start to learn how to use Android studio for a while and my teacher asks me the question above with many require. But I don't even get the concept to get and pass the data. Hope someone can tell me the concept with some coding.
CodePudding user response:
In case both fragments display on activity, you should use viewmodel, this is link for more infor and has code sample pass data via viewModel document . With other cases, you can use bundle to transfer data.
CodePudding user response:
You can choose FragmentResult API or viewModel. It depends on the nature of the data you want to pass. If it is just a simple "result", like your fragment A want to know you click which button in fragment B, the FragmentResult is enough. If you need to share data between A and B, viewModel is better.
FragmentResult:
fragment A
setFragmentResultListener("requestKey") { requestKey, 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
}
fragment B
button.setOnClickListener {
val result = "result"
// Use the Kotlin extension in the fragment-ktx artifact
setFragmentResult("requestKey", bundleOf("bundleKey" to result))
}