Android Studio 无法识别 setupWithNavController(navController)
的正确导入。
但它适用于 Google I/O 应用:
https://github.com/google/iosched
我创建了一个 hello world 项目,其中只添加了 NavHostFragment
:
activity_main.xml:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?android:attr/actionBarSize"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="FragmentTagUsage" />
</androidx.constraintlayout.widget.ConstraintLayout>
和这 3 个库:
build.gradle(应用级别):
dependencies {
constraints {
api "androidx.navigation:navigation-fragment-ktx:2.3.5"
api "androidx.navigation:navigation-ui-ktx:2.3.5"
api "com.google.android.material:material:1.3.0"
}
implementation "androidx.navigation:navigation-fragment-ktx:2.3.5"
implementation "androidx.navigation:navigation-ui-ktx:2.3.5"
implementation "com.google.android.material:material:1.3.0"
}
应用程序看不到 setupWithNavController
和 navController
作为参数方法。但在 Google I/O 应用程序中确实如此。
我尝试直接引用整个包名,但它只能识别 NavigationUI:
当我点击导入时,我确实看到了正确的库:
我尝试了无效缓存/重启和清理,构建所有但没有成功。
答案 0 :(得分:1)
你需要导航视图来使用设置导航控制器看起来像这样希望有帮助
MainActivity.kt
package com.example.yourpackagename
import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navView: BottomNavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)
val appBarConfiguration = AppBarConfiguration(setOf(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications))
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
}