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

Android两个Fragment间多数据传递问题:Bundle传参返回空值

Fragment间传参问题解决:Bundle修复+ViewModel入门

一、Bundle传参失败的原因及修复

你当前Bundle传参失效的核心问题是:FragmentTransaction只执行了commit,但没有将新创建的WeightTableFragment添加/替换到布局容器中,导致第二个Fragment从未被正确加载,自然拿不到参数。

修复后的第一个Fragment点击事件代码

addBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        weight[0] = edtNumber.getText().toString();
        sWeight = weight[0];
        
        // 推荐使用Fragment提供的newInstance方法传参(你已经实现了,别浪费)
        WeightTableFragment weightTableFragment = WeightTableFragment.newInstance(sWeight, currentDateAndTime);

        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        
        // 关键:添加replace或add方法,指定容器ID(比如你的布局里用来放Fragment的FrameLayout的id)
        fragmentTransaction.replace(R.id.fragment_container, weightTableFragment);
        // 可选:添加回退栈,让用户可以返回上一个Fragment
        fragmentTransaction.addToBackStack(null);
        
        fragmentTransaction.commit();
        Toast.makeText(getActivity(),weight[0] + currentDateAndTime, Toast.LENGTH_SHORT).show();
    }
});

补充说明

  • 一定要确保R.id.fragment_container是你Activity布局中用来承载Fragment的容器(通常是FrameLayout)的ID。
  • 使用你已经写好的newInstance方法传参比直接setArguments更规范,避免参数键名写错。

二、ViewModel工作原理及使用示例

ViewModel的核心作用是在多个Fragment/Activity间共享数据,且数据生命周期不受屏幕旋转等配置变化影响。同一个Activity下的多个Fragment,只要用ViewModelProvider(getActivity())获取ViewModel实例,拿到的就是同一个对象,自然能共享数据。

1. 定义ViewModel类

public class WeightViewModel extends ViewModel {
    // 用MutableLiveData来观察数据变化(如果需要监听更新的话)
    private MutableLiveData<String> weightData = new MutableLiveData<>();
    private MutableLiveData<String> dateData = new MutableLiveData<>();

    public void setWeight(String weight) {
        weightData.setValue(weight);
    }

    public void setDate(String date) {
        dateData.setValue(date);
    }

    public LiveData<String> getWeight() {
        return weightData;
    }

    public LiveData<String> getDate() {
        return dateData;
    }
}

2. 第一个Fragment中设置数据

// 在onCreateView中获取ViewModel,注意用getActivity()作为所有者
WeightViewModel weightViewModel = new ViewModelProvider(getActivity()).get(WeightViewModel.class);

addBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String inputWeight = edtNumber.getText().toString();
        // 设置数据到ViewModel
        weightViewModel.setWeight(inputWeight);
        weightViewModel.setDate(currentDateAndTime);
        
        // 切换到第二个Fragment
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, new WeightTableFragment());
        transaction.addToBackStack(null);
        transaction.commit();
    }
});

3. 第二个Fragment中获取数据

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_weight_table, container, false);
    TextView text = rootView.findViewById(R.id.weightDate);

    // 同样用getActivity()获取同一个ViewModel实例
    WeightViewModel weightViewModel = new ViewModelProvider(getActivity()).get(WeightViewModel.class);
    
    // 观察数据变化,一旦数据更新就刷新UI
    weightViewModel.getWeight().observe(getViewLifecycleOwner(), weight -> {
        weightViewModel.getDate().observe(getViewLifecycleOwner(), date -> {
            text.setText(date + ": " + weight);
        });
    });

    return rootView;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:45:42