Anywhere in a NavHostFragment
I can do findNavController().navigateUp()
Or, if in my Fragment I have a button to be used for navigation, I could do either:
editButton.setOnClickListener { v ->
v.findNavController().navigateUp()
}
or
editButton.setOnClickListener {
findNavController().navigateUp()
}
Why would I use one extension function vs the other when setting up a button click listener in a Fragment?
NavHostFragment provides an area within your layout for self-contained navigation to occur. NavHostFragment is intended to be used as the content area within a layout resource defining your app's chrome around it, e.g.: <androidx.drawerlayout.widget.DrawerLayout.
NavController is used to navigate from one destination to another destination which can be retrieved by following one of the static methods, NavHostFragment. findNavController(Fragment) Navigation. findNavController(Activity, @IdRes int viewId)
popBackStack() , the top-most fragment transaction is popped off of the stack. In other words, the transaction is reversed. If there are no more fragment transactions on the stack, and if you aren't using child fragments, the back event bubbles up to the activity.
They are almost the same, Fragment.findNavController()
is just a handy shortcut, it actually calls Navigation.findNavController(view)
at the end. Both of them are getting the NavController
from the root view of the fragment.
// NavHostFragment.java
public static NavController findNavController(@NonNull Fragment fragment) {
....
View view = fragment.getView();
if (view != null) {
return Navigation.findNavController(view);
}
...
}
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