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中添加了导航/ nav_file,还添加了defaultNavHost =“ true”
答案 0 :(得分:1)
根据上面的代码,单击按钮即可从一个片段导航到另一个片段,
Navigation类为您提供了createNavigateOnClickListner()方法,您只需传递片段操作ID。
尝试以下代码
mBtHome.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_mainFragment_to_homePageFragment));
答案 1 :(得分:1)
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)