'How can i get and pass the user input from one fragment to another fragment with only one mainactivity
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.
Solution 1:[1]
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.
Solution 2:[2]
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))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anh Luu |
| Solution 2 | Krahmal |
