IllegalStateException:链接没有设置 NavController

新手上路,请多包涵

我正在使用 Android 导航组件进行导航。我有一个 LoginFragment,它有一个转换为 SignUpFragment 的按钮。单击按钮时,我收到此错误。

 java.lang.IllegalStateException: View android.support.v7.widget.AppCompatButton{49d9bd1 VFED..C.. ...P.... 201,917-782,1061 #7f090172 app:id/signUpLink} does not have a NavController set

这是我的 nav_graph.xml

 <navigation xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        app:startDestination="@id/loginFragment">
        <fragment
            android:id="@+id/loginFragment"
            android:name="org.fossasia.openevent.app.core.auth.login.LoginFragment"
            android:label="login_fragment"
            tools:layout="@layout/login_fragment">
            <action
                android:id="@+id/action_loginFragment_to_signUpFragment"
                app:destination="@id/signUpFragment" />

        </fragment>
    </navigation>

这是 LoginFragment 中用于导航的代码 -

 binding.signUpLink.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_loginFragment_to_signUpFragment, null));

这是 NavHostFragment 的活动布局文件的摘录 -

 <FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:name="android.navigation.fragment.NavHostFragment"
    app:navGraph="@navigation/main_navigation"
    app:defaultNavHost="true"/>

原文由 Masquerade 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 648
2 个回答

更新的解决方案

实际上,Navigation 在 FrameLayout 中找不到 NavController。因此,将 <FrameLayout> 替换为 <fragment>

<fragment> 标签内添加以下内容 -

 android:name="androidx.navigation.fragment.NavHostFragment"

进行更改后,代码将与此类似 -

  <fragment
       android:id="@+id/fragment_container"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       app:layout_behavior="@string/appbar_scrolling_view_behavior"
       android:name="androidx.navigation.fragment.NavHostFragment"
       app:navGraph="@navigation/main_navigation"
       app:defaultNavHost="true"/>

原文由 Masquerade 发布,翻译遵循 CC BY-SA 4.0 许可协议

FragmentViewContainer 的更新答案

确保你有

android:name="androidx.navigation.fragment.NavHostFragment"

而不是你想要的片段作为开始片段。 (起始目的地在导航图中定义)。

原文由 Otziii 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题