I am using navigation component for the app I am working on currently, I ran into a problem with navigation graph and sub navigation graphs.
Basically, I have sub_nav_graph_1
and sub_nav_graph_2
, each does a simple flow and then pops all the way back to the fragment which initiated it, problem is when I needed to create a flow that goes like following, while I'm in fragment number 2 in sub_nav_graph_1
, I want to start flow of sub_nav_graph_2
all the way to the end but when it ends I want to know whether it ended successfully or not (I want to get that piece of information in "fragment number 2" of sub_nav_graph_1
) but there was no way to so using navigation component, I was looking for something like "start sub navigation graph for result" and regardless who starts that navigation graph it always goes back to it after it finishes the flow and returns the result.
ok so i have found an answer to my question , Android supports passing data between fragments or between fragments and activities which is 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"
FragmentA.kt
class FragmentA : Fragment() {
//do not forget to unregister your listener
override fun onPause() {
super.onPause()
clearFragmentResultListener(FlagCustomerConfirmationFragment.REQUEST_KEY)
}
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
implement logic which basically navigating up back to the fragment where you set up the listener
}
}
}