Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View.findNavController() vs Fragment.findNavController()

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?

like image 939
liminal Avatar asked Sep 08 '18 01:09

liminal


People also ask

What is NAV host 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.

What is findNavController in Android?

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)

What is popBackStack fragment Android?

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.


1 Answers

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);
    }
    ...
}
like image 189
jaychang0917 Avatar answered Sep 19 '22 05:09

jaychang0917