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

Android Studio中使用Navigation实现Fragment间扫码数据传递的方法咨询

可用实现方案

你当前的问题是误用了Activity间传参的Intent方式,Navigation组件跳转Fragment本身提供了两种稳定的传参方案:


方案1:Bundle直接传参(无需额外配置,适合快速开发)

跳转侧修改(扫码Fragment)

修正你的回调代码如下:

codeScanner.setDecodeCallback(new DecodeCallback() {
        @Override
        public void onDecoded(@NonNull Result result) {
            getActivity().runOnUiThread(new Runnable(){
                @Override
                public void run(){
                    String resultText = result.getText();
                    if(resultText != null) {
                        // 修复原代码笔误:原resultData应为result.getText()
                        String[] parkingdata = resultText.split(",");
                        // 封装参数到Bundle
                        Bundle paramBundle = new Bundle();
                        paramBundle.putString("parkingName", parkingdata[0]);
                        paramBundle.putString("parkingPrice", parkingdata[1]);
                        // 跳转时携带参数
                        Navigation.findNavController(view).navigate(R.id.action_qrSession_to_addSession, paramBundle);
                    }
                }
            });
        }
    });

接收侧处理(addParkingSession Fragment)

在该Fragment的onViewCreated生命周期中取值即可:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Bundle args = getArguments();
    if (args != null) {
        String parkingName = args.getString("parkingName");
        String parkingPrice = args.getString("parkingPrice");
        // 后续业务逻辑自行实现
    }
}

方案2:Safe Args插件传参(类型安全,推荐正式项目使用)

如果需要避免参数名拼写错误、类型不匹配的隐性bug,可以使用官方提供的Safe Args插件:

  1. 在项目级build.gradle中引入Safe Args插件依赖
  2. 在导航图的addSession目的地节点中添加<argument>标签,声明参数名、类型、默认值
  3. 跳转时使用自动生成的QrSessionDirections类设置参数,接收时用AddSessionArgs类直接解析参数,无需手动处理key值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:54:00