首页 > 解决方案 > 如何与 recyclerview 适配器中的 Viewmodel 交互?

问题描述

我见过类似的问题,但对我没有帮助。我会尽量具体说明我的问题。我的购物车中有产品列表。当我搜索产品时,我希望为购物车中已经存在的商品禁用“添加到购物车”按钮。

购物车项目列表在我的视图模型中。

我的方法如下 - 当为特定位置调用 onBindViewHolder 时,我需要搜索当前项目(产品)是否存在于购物车中存在的项目列表中,如果存在则禁用按钮。

这里我的问题是购物车在 Viewmodel 中,我发现自己无法从 OnBindViewholder 方法调用 viewmodel。

有没有更好的方法来做到这一点?

@Override
public void onBindViewHolder(@NonNull ProductAdapter.OurViewHolder viewHolder, int i) {
    Products currentItem = adapterData.get(i);
    viewHolder.productNamesFragmentItemsBinding.setProductName(currentItem);
    if (currentItem.getPhotoUris() != null) {
    Picasso.get().load(currentItem.getPhotoUris().get(0)).into(viewHolder.productNamesFragmentItemsBinding.ivProductImage);

    //  now i want to search if current item is present in cart (cart is in viewModel), if item
        // is present in cart then disable "Add to Cart" button for current position
        
        //--------------todo : how to do it ??? -----------------------------------
    }
}

标签: androidmvvm

解决方案


使用 ViewModelProvider 进行初始化。您可以在构造函数中进行一次这样的初始化(对不起命名,我为一个项目编写了这段代码。我只是从那里复制粘贴:()

    public class CartChildAdapter extends RecyclerView.Adapter<CartChildAdapter.CartHolder> {
    
        private ShoppingCartWishListViewModel shoppingCartWishListViewModel;
    
        public CartChildAdapter(Context context) {
            // this is the line you are looking for. Cast context with FragmentActivity
            this.shoppingCartWishListViewModel = new ViewModelProvider((FragmentActivity)context).get(ShoppingCartWishListViewModel.class);
        }
    
     
        @Override
        public void onBindViewHolder(@NonNull CartChildAdapter.CartHolder holder, int position) {
           // call from here
           this.shoppingCartWishListViewModel.getMyProduct(your parameters may be).observe(this,..){
             ......... Your Codes           
}
 }

推荐阅读