简体   繁体   English

如何找到带有视图绑定的导航控制器?

[英]How to find navcontroller with view binding?

I am using view binding in my app.我在我的应用程序中使用视图绑定。 But now I am facing issue with finding navcontroller with view binding.但现在我面临着寻找带有视图绑定的导航控制器的问题。

If I use traditional way to set content view with layout, I can easily find navcontroller with this piece of code.如果我使用传统的方式来设置带有布局的内容视图,我可以通过这段代码轻松找到导航控制器。

Navigation.findNavController(this, R.id.nav_host_fragment)

But if I use view binding to set content view how can I find navcontroller since the above code requires ID of navHostFragment but view bending returns fragment if I give binding.navHostFragment但是,如果使用视图结合,因为上面的代码需要navHostFragment的ID设置内容视图我怎么能找到navcontroller但查看弯曲回报片段,如果我给binding.navHostFragment

ViewBinding , As its name implies, is used to bind views not to bind resource identifiers . ViewBinding ,顾名思义,用于绑定视图而不是绑定资源标识符

What ViewBinding offers you in its simple form, that you don't have to findViewById(view_id) anymore; ViewBinding以简单的形式为您提供什么,您不再需要findViewById(view_id) instead it offers binding.myView .. Both cases returns a view.相反,它提供binding.myView .. 两种情况都返回一个视图。

But in the NavController context, you don't have to get a view (but a resource id), so that view binding won't benefit you (again because it binds views not ids).但是在NavController上下文中,您不必获取视图(而是资源 ID),因此视图绑定不会使您受益(再次因为它绑定的是视图而不是 ID)。

So, you will have to use the same code to get the NavController :因此,您必须使用相同的代码来获取NavController

Navigation.findNavController(this, R.id.nav_host_fragment)

Fist thing you have to use FragmentContainerView instead of fragment don't forget to use the same name attribute and that's it!拳的事情,你必须使用FragmentContainerView而不是片段不要忘记使用相同的名称属性,这就是它! now you can find it in the binding elements现在您可以在绑定元素中找到它

so as example you have to change this :所以作为例子,你必须改变这一点:

        <fragment
        android:id="@+id/mainFragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation" />

into this :进入这个:

        <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM