使用视图绑定导航

使用视图绑定导航

本文介绍了使用视图绑定导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用视图绑定替换所有 findViewById.但是,我无法使用 View Binding 更改 NavController 代码行.

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)

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

我该怎么做?

推荐答案

您不能用视图绑定替换它.findNavController 不仅仅是在布局中查找视图.

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

查看源代码 这里

 /**
 * 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.

这篇关于使用视图绑定导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:17