I am trying to implement fragment result API in my application. I need to show DialogFragment inside Fragment and send result from dialog fragment to fragment when dialog buttons was clicked. So in my dialog fragment when button was clicked I making smth like this:
setFragmentResult(requestKey, bundleOf(RESULT to result))
And I'am trying to retrieve result in my fragment inside onCreate()
:
childFragmentManager.setFragmentResultListener(requestKey, this) { _, bundle ->
val result = bundle.getInt(DialogFragment.RESULT)
// some code
}
Everything works well, but there is one problem. The requestKey
I use when calling the setFragmentResult
in my dialog fragment is dynamic.
That is, the dialog can be opened inside the fragment in different cases. And I need to distinguish between these cases. To do this, I send a different request key to the dialog fragment.
But how do I, when receiving a result in a fragment, distinguish this result by key. If I do this inside the onCreate()
method.
That is, I want to do something like this:
childFragmentManager.setFragmentResultListener(requestKey, this) { requestKey, bundle ->
when(requestKey) {
"FIRST_CASE" -> { // some code }
"SECOND_CASE" -> { // some code }
}
}
But I do not understand how this can be implemented if this method (setFragmentResultListener
) already requires a requestKey
as an argument. Where should I take it from?
If my requestKey
was static I would create a constant inside the dialog fragment and use it. But my requestKey
is dynamic.
Please help me. I did not find a suitable example for me on the Internet. And at the moment I don’t understand how this can be implemented in the context of a clean architecture with MVVM.
P.S. Here is an example of what I want to implement:
A fragment that contains two buttons (e.g. A
, B
). By clicking on each of the buttons, dialog fragment opens, with different text. Inside the dialog there is also a button, by clicking on which the result is transferred to the fragment. I need to process this result differently, depending on which button was pressed on the fragment (A or B). To do this, I wanted to distinguish by request key.