如何在AndroidX中设置导航控制器? [英] How to set Nav Controller in AndroidX?

查看:231
本文介绍了如何在AndroidX中设置导航控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将以下活动布局与fragmentBottomNavigationView一起使用:

I'm using the following activity layout with a fragment and a BottomNavigationView:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/fragment"
        android:layout_weight="1"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:newGraph="@navigation/navigation_bottom"
        app:defaultNavHost="true"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bottom_navigation_view"
        app:menu="@menu/bottom_navigation_menu"/>
</LinearLayout>

在我的活动中,我正在尝试为此设置导航控制器,但出现以下错误:

In my activity, I'm trying to setup the Nav Controller this but I'm getting the following error:

无法解析方法'setupWithNavController(androidx.navigation.NavController)'

Cannot resolve method 'setupWithNavController(androidx.navigation.NavController)'

这是我尝试过的:

navController = Navigation.findNavController(this, R.id.fragment);
BottomNavigationView bnv = findViewById(R.id.bottom_navigation_view);
bnv.setupWithNavController(navController); //Error
NavigationUI.setupActionBarWithNavController(this, navController);

我的依赖项:

implementation 'android.arch.navigation:navigation-fragment:1.0.0-rc02'
implementation 'android.arch.navigation:navigation-ui:1.0.0-rc02'

我该如何连接?谢谢!

推荐答案

语法bnv.setupWithNavController使用Kotlin扩展方法-您必须使用Kotlin和-ktx依赖项才能访问Kotlin扩展,具体方法请参见声明依赖项文档:

The syntax bnv.setupWithNavController uses a Kotlin extension method - you have to use Kotlin and the -ktx dependencies to have access to Kotlin extensions as per the note in the Declaring dependencies documentation:

implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-rc02'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-rc02'

如果要编写Java代码,则需要直接使用NavigationUI方法:

If you're writing Java code, you need to use the NavigationUI methods directly:

NavigationUI.setupWithNavController(bnv, navController);

这篇关于如何在AndroidX中设置导航控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆