You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Navigation Component在Fragment内加载Fragment时找不到导航action如何解决

报错原因
    1. 你调用findNavController()获取的是HomeFragment自身所属的父层级NavController,不是你在HomeFragment布局里内嵌的子NavHostFragment对应的控制器,父导航图中根本没有你定义的action_homeFragment2_to_homeBottomOneFragment这个动作,所以直接找不到目标。
    1. 导航图层级逻辑错误:你把HomeFragment的节点(id为homeFragment2)写到了子导航图@navigation/bottm_navi里,但子导航图是给HomeFragment内部的子Fragment导航用的,HomeFragment本身是在父级导航图里注册的,id是homeFragment,和子导航图里的homeFragment2不匹配,自然找不到对应action。
修复方案

第一步:修正子导航图@navigation/bottm_navi

删掉子导航图里冗余的HomeFragment节点代码,修正后的导航图如下:

<?xml version="1.0" encoding="utf-8"?>
<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/bottm_navi"
    app:startDestination="@id/homeBottomOneFragment">

    <fragment
        android:id="@+id/homeBottomOneFragment"
        android:name="com.krassier.customer.ui.home.bottom.HomeBottomOneFragment"
        android:label="fragment_home_bottom_one"
        tools:layout="@layout/fragment_home_bottom_one" />
    <fragment
        android:id="@+id/homeBottomTwoFragment"
        android:name="com.krassier.customer.ui.home.bottom.HomeBottomTwoFragment"
        android:label="fragment_home_bottom_two"
        tools:layout="@layout/fragment_home_bottom_two" />
    <fragment
        android:id="@+id/homeBottomFourFragment"
        android:name="com.krassier.customer.ui.home.bottom.HomeBottomFourFragment"
        android:label="fragment_home_bottom_four"
        tools:layout="@layout/fragment_home_bottom_four" />
    <fragment
        android:id="@+id/homeBottomThreeFragment"
        android:name="com.krassier.customer.ui.home.bottom.HomeBottomThreeFragment"
        android:label="fragment_home_bottom_three"
        tools:layout="@layout/fragment_home_bottom_three" />
</navigation>

因为子导航图的startDestination已经设置为第一个子Fragment,子NavHost加载后会自动加载首页,不需要额外定义跳转动作。

第二步:在HomeFragment中获取正确的子NavController

不要用默认的findNavController(),要通过childFragmentManager获取自己布局里内嵌的子NavHost的控制器,跳转代码修改为:

// 先获取子NavHostFragment实例
val childNavHost = childFragmentManager.findFragmentById(R.id.fragment) as NavHostFragment
val childNavController = childNavHost.navController
// 直接跳转到对应子Fragment的id即可,不需要额外定义action
childNavController.navigate(R.id.homeBottomOneFragment)

后续点击底部导航切换其他子Fragment时,也用这个childNavController调用navigate方法传入对应子Fragment的id即可。

内容的提问来源于stack exchange,提问作者karteek thati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:09:03