android - 如何与 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 ??? -----------------------------------
}
}
解决方案
使用 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
}
}
推荐阅读
- php - 使用 AbstractNormalizer::ATTRIBUTES 规范化嵌套对象
- ruby-on-rails - Docker Web 映像现在可以与 rspec gem 一起使用
- python - 在 TensorFlow Hub 模型上使用 TensorBoard 时出现 InvalidArgumentError
- android - 每次在带有导航的底部导航视图中选择一个选项卡时,都会创建片段的新实例
- reactjs - React Router - 在变量或组件中分组路由
- java - 如何避免多次空检查,如果需要在每次检查后做一些事情
- swift - 为什么从不调用 DispatchGroup deinit?
- java - 已解析的 Groovy 脚本的(反)序列化
- apache-nifi - 有没有办法以编程方式接收 NiFi 远程进程组的目标 uri?
- string - 如何转义 SPARQL 字符串中的括号?