使用视图绑定导航

Tha*_*Zin 5 android-navigation android-viewbinding

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

val navController = findNavController(this, R.id.mainHostFragment)
Run Code Online (Sandbox Code Playgroud)

var binding : ActivityMainBinding
val navController = findNavController(this, binding.mainHostFragment)
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Som*_*mar 7

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

在这里查看源代码

/**
* 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");
}
Run Code Online (Sandbox Code Playgroud)

它的作用不仅仅是找到控制器。它遍历、创建片段、创建视图并抛出异常。

视图绑定只是生成一个绑定类,其中包含布局的所有视图。它不适用于查找应用程序的导航控制器。