首页 > 解决方案 > 导航控制器从 startDestination 片段导航获取异常

问题描述

java.lang.IllegalArgumentException: ID does not reference a View inside this Activity

    mBtHome.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {



                    Navigation.findNavController(getActivity(), R.id.homePageFragment);
                }
            });  

startDestination 片段内的 mBtHome 按钮

导航图 xml 文件。

<navigation 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:id="@+id/nav_file"
    app:startDestination="@id/mainFragment">
    <fragment
        android:id="@+id/mainFragment"
        android:name="com.example.libin.navigationhelphertest.ui.main.MainFragment"
        android:label="main_fragment"
        tools:layout="@layout/main_fragment">
        <action
            android:id="@+id/action_mainFragment_to_homePageFragment"
            app:destination="@id/homePageFragment" />
        <action
            android:id="@+id/action_mainFragment_to_usersListFragment"
            app:destination="@id/usersListFragment" />
    </fragment>
    <fragment
        android:id="@+id/homePageFragment"
        android:name="com.example.libin.navigationhelphertest.ui.main.HomePageFragment"
        android:label="fragment_home_page"
        tools:layout="@layout/fragment_home_page" />
    <fragment
        android:id="@+id/usersListFragment"
        android:name="com.example.libin.navigationhelphertest.ui.main.UsersListFragment"
        android:label="fragment_users_list"
        tools:layout="@layout/fragment_users_list" />
</navigation>

在 MainActivity xml 文件中添加了导航/导航文件 NavHostFragment 也包括在内,还添加了 defaultNavHost= "true"

标签: androidnavigationcontrollerandroid-jetpackandroid-architecture-navigation

解决方案


根据上面的代码,通过单击按钮从一个片段导航到另一个片段,有很多方法。

导航类为您提供了 createNavigateOnClickListner() 方法,您只需传递片段操作 ID。

试试下面的代码

 mBtHome.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_mainFragment_to_homePageFragment));

推荐阅读