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?
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);
}
...
}