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

如何在DeliteFragment的onViewCreated方法中获取跨Fragment传递的数据并传给RecyclerView适配器

如何在DeliteFragment的onViewCreated方法中获取跨Fragment传递的数据并传给RecyclerView适配器

看起来你遇到的核心问题是FragmentResult的异步回调特性导致的——当你在onViewCreated里直接尝试使用nameDayTrain时,回调还没触发,数据根本没拿到,自然传不到RecyclerView适配器里。我来帮你一步步解决这个问题:

问题根源拆解

getParentFragmentManager().setFragmentResultListener()的onFragmentResult方法是异步执行的:当你的onViewCreated执行到String nameDayTrainRW = nameDayTrain;这一行时,回调逻辑还没跑,nameDayTrain还是空值,所以后续初始化的适配器自然拿不到有效数据。

解决方案代码修改

我们调整逻辑顺序,先完成RecyclerView的基础配置,等回调拿到数据后再初始化数据源和适配器:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    
    // 第一步:先初始化RecyclerView的基础配置(必须设置布局管理器!)
    recyclerView = view.findViewById(R.id.train_delite_recycleView);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // 根据你的需求换成GridLayoutManager等

    // 第二步:设置FragmentResultListener,等待接收数据
    getParentFragmentManager().setFragmentResultListener("text from WOF to AFJ", this, new FragmentResultListener() {
        @Override
        public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle textBundle) {
            // 这里才是真正拿到数据的地方
            Integer number_workout_train_position = textBundle.getInt("text from WOF to AFJ");
            String nameDayTrain = new CardSourceImplDayTrain(getActivity())
                                    .getCardData(number_workout_train_position)
                                    .getTitle()
                                    .toString();
            
            // 拿到有效数据后,再初始化数据源和适配器
            cardSource = new CardSourceImplDelite(getActivity().getApplicationContext(), nameDayTrain, nameDayTrain);
            adapter = new itemAdapterDelite(cardSource);
            // 最后把适配器绑定到RecyclerView上
            recyclerView.setAdapter(adapter);
        }
    });
}

额外注意:确保WorkoutFragment的数据发送逻辑正确

你需要在WorkoutFragment跳转DeliteFragment之前,先通过setFragmentResult发送数据,否则DeliteFragment的监听器收不到内容:

// 在WorkoutFragment中,跳转前先发送数据
Bundle resultBundle = new Bundle();
resultBundle.putInt("text from WOF to AFJ", 你的目标position值); // 替换成实际要传递的位置数值
getParentFragmentManager().setFragmentResult("text from WOF to AFJ", resultBundle);

// 再执行Fragment跳转逻辑
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new DeliteFragment());
fragmentTransaction.commit();

补充提醒

  • 一定要保证发送和接收的requestKey完全一致(都是"text from WOF to AFJ"),否则监听器不会触发回调。
  • 如果你的CardSourceImplDelite是异步加载数据的(比如从数据库/网络拉取),记得在数据加载完成后调用adapter.notifyDataSetChanged()来刷新RecyclerView。

备注:内容来源于stack exchange,提问作者Павел К

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 09:43:00