导航控制器从开始导航目标片段出现异常


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);
}
});  

开始目标片段内的 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>

navigation/nav_file 添加了在 MainActivity xml 文件 NavHostFragment 也包括在内,也添加了 defaultNavHost= "true"

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

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

尝试以下代码

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

R.id.homePageFragment 不是 NavHostFragment 像你一样做

<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragment_container_view"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/motion_layout_graph" />

并像这样调用代码

Navigation.findNavController(requireActivity(), R.id.fragment_container_view).navigate(R.id.show_one)

相关内容

最新更新