android - 导航控制器从 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"
解决方案
根据上面的代码,通过单击按钮从一个片段导航到另一个片段,有很多方法。
导航类为您提供了 createNavigateOnClickListner() 方法,您只需传递片段操作 ID。
试试下面的代码
mBtHome.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_mainFragment_to_homePageFragment));
推荐阅读
- python - Retrieve a Card with Customer 引发错误
- common-lisp - 有没有办法在 Common Lisp 中使用迭代并同时避免副作用?
- javascript - 范围计数器的值增加 1 会达到 10 次 $digest() 迭代。中止错误消息
- c# - 按给定顺序更改序列
- javascript - 组件挂载时onClick的函数触发
- reactjs - 删除数组中的特定值并添加新的更新值
- json - 使用 jq 提取内部数组匹配值
- python - 如何在这个矩阵中排列一个向量?
- python - 修改功能性 python compose() 以返回所有中间值的列表
- python-3.x - 如何使用 3X3 矩阵中的数据绘制 2D 轮廓?