为什么我的导航控制器找不到我已经拥有的 ID?

2022-09-01 21:57:56

每次当我启动我的应用程序时,它都会崩溃,Logcat会说:

由以下原因引起:java.lang.IllegalArgumentException: ID 不引用此活动内的视图

所以我认为这是说找不到ID,但这是我的Java文件和XML文件相互对应。爪哇岛:

NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);

XML:

<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.285"
        app:navGraph="@navigation/mobile_navigation" />

Logcat 显示失败,因为 java 文件 ID 未引用此活动内的视图。但我清楚地输入了ID:nav_host_fragment。我不知道出了什么问题,当我在Android Studio中时,它没有报告任何错误。请帮忙。


答案 1

Navigation.findNavController依赖于 ,这仅在您调用后才有效 - 即,实际将您的视图添加到您的活动中。findViewById()setContentView()


答案 2

使用适当的控制器来避免 ID 不引用此活动或片段中的视图?

如果您使用的是 Java

活动使用中

NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment)

在片段使用中

NavController navController = NavHostFragment.findNavController(this)
// or
NavHostFragment.findNavController(view)

如果您使用的是 kotlin

活动使用中

val navController = findNavController(R.id.nav_host_fragment)

在片段使用中

val navController = findNavController()

推荐