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

如何从NavGraphA中的Fragment向NavGraphB的起始目的地Fragment传递参数

实现参数跨导航图传递的步骤

步骤1:在导航图B的根节点声明参数

你是从导航图A直接跳转到整个导航图B(id为flow_direct_service),所以需要先在导航图B的根节点声明要接收的isControlled参数,参数类型和默认值要和FragmentB里定义的保持一致,这样Navigation组件会自动把传入导航图B的参数透传给它的起始目的地FragmentB:

<!-- NavigationGraphB.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/flow_direct_service"
    app:startDestination="@id/flow_03_step_01">
    <!-- 新增根节点参数声明 -->
    <argument
        android:name="isControlled"
        android:defaultValue="false"
        app:argType="boolean"/>
    
    <fragment
        android:id="@+id/flow_03_step_01"
        android:name="wfm.in.enel.com.modulotecnico.utenza.flow03.step01.FragmentB"
        android:label="@string/direct_service_activation"
        tools:layout="@layout/flow03_step_01">
        <argument android:name="isControlled"
            android:defaultValue="false"
            app:argType="boolean"/>
        <action
            android:id="@+id/action_flow_03_step_01_to_step10"
            app:destination="@id/step10" />
    </fragment>
</navigation>

步骤2:在FragmentA中跳转时传入参数

写法1:手动构造Bundle传参

// FragmentA中的跳转逻辑
val bundle = bundleOf("isControlled" to true) // 替换为实际要传递的布尔值
findNavController().navigate(R.id.action_step01_to_flow_direct_service, bundle)

写法2:用Safe Args插件类型安全传参(推荐)

如果项目已启用Safe Args插件,可直接用自动生成的方向类传参,避免手动写参数名出错:

// FragmentA中的跳转逻辑
val direction = FragmentADirections.actionStep01ToFlowDirectService(isControlled = true)
findNavController().navigate(direction)

步骤3:在FragmentB中接收参数

手动从Bundle取值

// FragmentB生命周期方法中获取
val isControlled = arguments?.getBoolean("isControlled") ?: false

用Safe Args取值

// FragmentB中声明参数接收
val args: FragmentBArgs by navArgs()

// 直接调用属性取值
val isControlled = args.isControlled

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:54:04