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

如何在Fragment中正确配置RecyclerView并关联ViewModel数据?

在Fragment中正确配置RecyclerView与ViewModel的关联

你当前直接用本地DummyDatas实例给Adapter传数据,没有利用ViewModel中已准备好的mProducts LiveData,正确的做法是通过观察ViewModel的数据源来驱动RecyclerView更新,具体操作如下:

1. 补全RecyclerView基础配置

首先要给RecyclerView设置布局管理器(现有代码缺失该配置,无布局管理器RecyclerView无法正常显示),同时初始化空数据的Adapter。

2. 监听ViewModel的LiveData数据源

通过observe方法监听ViewModel中商品数据的变化,数据更新时同步更新Adapter的数据集并通知刷新。


修改后的Fragment代码

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    DashboardViewModel dashboardViewModel =
            new ViewModelProvider(this).get(DashboardViewModel.class);

    binding = FragmentDashboardBinding.inflate(inflater, container, false);
    View root = binding.getRoot();

    // 监听TextView数据
    final TextView textView = binding.textDashboard;
    dashboardViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);

    // 配置RecyclerView
    RecyclerView recyclerView = binding.recyclerView;
    // 设置布局管理器,此处以LinearLayoutManager为例
    recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
    // 初始化空数据Adapter
    ProductAdapter productAdapter = new ProductAdapter(new ArrayList<>());
    recyclerView.setAdapter(productAdapter);

    // 监听ViewModel中的商品数据变化
    dashboardViewModel.getProducts().observe(getViewLifecycleOwner(), products -> {
        // 更新Adapter数据集
        productAdapter.setProducts(products);
        // 通知Adapter数据已变更
        productAdapter.notifyDataSetChanged();
    });

    return root;
}

给ProductAdapter添加数据更新方法

需要在ProductAdapter中新增一个更新数据集的方法,方便数据变化时调用:

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
    private List<Product> mProducts;

    // 构造方法
    public ProductAdapter(List<Product> products) {
        this.mProducts = products;
    }

    // 新增:更新数据集的方法
    public void setProducts(List<Product> products) {
        this.mProducts = products;
    }

    // ViewHolder、onCreateViewHolder、onBindViewHolder等其他方法保持原有逻辑即可
}

ViewModel部分说明

你的ViewModel代码已正确将商品数据存入MutableLiveData并对外暴露LiveData接口,这部分无需修改。后续如果需要从网络/数据库加载数据,只需在ViewModel中调用mProducts.setValue()或mProducts.postValue()更新数据,Fragment会自动收到通知并刷新RecyclerView。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:40:17