Learn How To Start A Fragment For Result Without Hassle Using Navigation Component.
class FragmentA : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Observe the result to be set by Fragment B in the stateHandle of the currentBackStackEntry
val currentBackStackEntry = findNavController().currentBackStackEntry
val savedStateHandle = currentBackStackEntry?.savedStateHandle
savedStateHandle?.getLiveData<String>(RESULT_FROM_FRAGMENT_B)
?.observe(currentBackStackEntry, Observer { result ->
print(result)
})
}
private fun navigateToFragmentB() {
val navDirection = FragmentADirection.actionFragmentAToFragmentB()
findNavController().navigate(navDirection)
}
companion object {
const val RESULT_FROM_FRAGMENT_B = "RESULT_FROM_FRAGMENT_B"
}
}
class FragmentB : Fragment() {
private fun navigateBackToFragmentA() {
//Setting the result in the stateHandle of the previousBackStackEntry before navigating back to Fragment A
//will allow Fragment A to access the result in the stateHandle of its currentBackStackEntry
val savedStateHandle = findNavController().previousBackStackEntry?.savedStateHandle
savedStateHandle?.set(FragmentA.RESULT_FROM_FRAGMENT_B, "result")
findNavController().navigateUp()
}
}
Looking for a new challenge? Join Our Team
From us to your inbox weekly.
My question is if we are observing a String in Fragment A, then why we pass a Boolean in fragment B?
// Navigation
implementation "android.arch.navigation:navigation-fragment-ktx:$version_navigation"
implementation "android.arch.navigation:navigation-ui-ktx:$version_navigation"
I cannot access currentBackStackEntry using: navController.currentBackStackEntry... Won't compile. Anything I am missing here?