hello my problem is the following, I have 2 fragments, one receives with SetFragmentResultListener and another sends with setFragmentResult
The problem is that setFragmentResult does not work inside an OnClickListener but it does work outside
Parent
setFragmentResultListener("scannedCode") { requestKey, bundle ->
val result = bundle.getString("code")
Log.i("MYLOG-find","$result")
}
Child - It Work
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_scan, container, false)
setFragmentResult("scannedCode", bundleOf("code" to "pedro"))
return view
}
Child - It doesn't Work
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_scan, container, false)
view.textView2.setOnClickListener {
setFragmentResult("scannedCode", bundleOf("code" to "pedro"))
}
return view
}
As per @ianhanniballake's answer, I went a bit further, because I had a similar problem, and read the documentation he referred (specially, the Receive results in the host activity section). One of the keys in making inter-fragment communication (parent-child) is to use activity's supportFragmentManager methods to perform the information exchange. Example:
requireActivity().supportFragmentManager
.setFragmentResultListener("whatever_id_you_use", viewLifecycleOwner) {
// Your code for listener
}
requireActivity().supportFragmentManager
.setFragmentResult("whatever_id_you_use", bundle_with_results)
"whatever_id_you_use" is the requestKey depicted in documentation, which is the index the activity will look for when assigning a listener to its result. Doing this way should keep the listeners in sync with the lifecycle, while simplifying own listener's implementation.
In the case of passing data from Child to Parent fragment, using the childFragmentManager is the key when setting the resultListener on the parent fragment.
onCreate()):childFragmentManager.setFragmentResultListener("requestKey", this ) { requestKey, bundle ->
val resultReceived = bundle.getString("bundleKey")
// do something with the result
// ...
}
val resultToBeSent = "result"
setFragmentResult("requestKey", bundleOf("bundleKey" to resultToBeSent))
More useful information about the communication between fragments can be found in this medium article: The modern way to pass data between fragments and of course in the official Android documentation: Communicating with fragments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With