View.findNavController() vs Fragment.findNavController()

liminal picture liminal · Sep 8, 2018 · Viewed 14.2k times · Source

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?

Answer

jaychang0917 picture jaychang0917 · Sep 8, 2018

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