Search code examples
android-navigationandroid-viewbinding

Navigation with View Binding


I'm trying to replace all findViewById using View Binding. But, I can't change my NavController code line using View Binding.

val navController = findNavController(this, R.id.mainHostFragment)

to

var binding : ActivityMainBinding
val navController = findNavController(this, binding.mainHostFragment)

How can I do that?


Solution

  • You can't replace it with View Binding. findNavController does more than finding the view in the layout.

    Have a look at the source code here

    /**
    * Find a {@link NavController} given a local {@link Fragment}.
    *
    * <p>This method will locate the {@link NavController} associated with this Fragment,
    * looking first for a {@link NavHostFragment} along the given Fragment's parent chain.
    * If a {@link NavController} is not found, this method will look for one along this
    * Fragment's {@link Fragment#getView() view hierarchy} as specified by
    * {@link Navigation#findNavController(View)}.</p>
    *
    * @param fragment the locally scoped Fragment for navigation
    * @return the locally scoped {@link NavController} for navigating from this {@link Fragment}
    * @throws IllegalStateException if the given Fragment does not correspond with a
    * {@link NavHost} or is not within a NavHost.
    */
    @NonNull
    public static NavController findNavController(@NonNull Fragment fragment) {
    Fragment findFragment = fragment;
    while (findFragment != null) {
        if (findFragment instanceof NavHostFragment) {
            return ((NavHostFragment) findFragment).getNavController();
        }
        Fragment primaryNavFragment = findFragment.getParentFragmentManager()
                .getPrimaryNavigationFragment();
        if (primaryNavFragment instanceof NavHostFragment) {
            return ((NavHostFragment) primaryNavFragment).getNavController();
        }
        findFragment = findFragment.getParentFragment();
    }
    // Try looking for one associated with the view instead, if applicable
    View view = fragment.getView();
    if (view != null) {
        return Navigation.findNavController(view);
    }
    throw new IllegalStateException("Fragment " + fragment
            + " does not have a NavController set");
    }
    

    It does more than just finding the controller. It traverses, creates fragment, creates views and throw an exception.

    View binding just generates a binding class with all the views of your layout in it. It is not meant for finding the navigation controller of the app.