如何在RecyclerView Adapter中使用Architecture Components ViewModel?

时间:2017-06-12 08:59:57

标签: java android android-architecture-components

我有多个ViewHolders在垂直RecyclerView中作为单独的视图工作。 我正在练习新的Architecture Components ViewModel。

在我的ViewModel中我有几个我想要观察的MutableLiveData列表。但我怎么称呼

ViewModelProviders.of((AppCompatActivity)getActivity()).get(FilterViewModel.class)

mFilterViewModel.getCountries().observe(this, new Observer<ArrayList<TagModel>>() {
            @Override
            public void onChanged(@Nullable ArrayList<TagModel> tagModels) {

            }
        });

不泄漏活动或将活动保存在适配器内。

我的ViewModel

public class FilterViewModel extends ViewModel {

private final MutableLiveData<ArrayList<TagModel>> mCountries;
private final MutableLiveData<ArrayList<TagModel>> mSelectedCountryProvinceList;
private final MutableLiveData<ArrayList<TagModel>> mDistanceList;

public FilterViewModel(){

    mCountries = new MutableLiveData<>();
    mSelectedCountryProvinceList = new MutableLiveData<>();
    mDistanceList = new MutableLiveData<>();

    TagStore.getInstance().subscribe(new StoreObserver<TagSearchList>() {
        @Override
        public void update(TagSearchList object) {
            mCountries.setValue(object.getCountries());
        }

        @Override
        public void update(int id, TagSearchList object) {
            if (id == 5){
                TagStore.getInstance().unSubcribe(this);
                update(object);
            }
        }

        @Override
        public void error(String error) {

        }
    }).get(5,"parent");

    TagStore.getInstance().subscribe(new StoreObserver<TagSearchList>() {
        @Override
        public void update(TagSearchList object) {
            mSelectedCountryProvinceList.setValue(object.toList());
        }

        @Override
        public void update(int id, TagSearchList object) {
            if (id == 6){
                TagStore.getInstance().unSubcribe(this);
                update(object);
            }
        }

        @Override
        public void error(String error) {

        }
    }).get(6,"parent");

    TagStore.getInstance().subscribe(new StoreObserver<TagSearchList>() {
        @Override
        public void update(TagSearchList object) {
            mDistanceList.setValue(object.toList());
        }

        @Override
        public void update(int id, TagSearchList object) {
            if (id == 51){
                TagStore.getInstance().unSubcribe(this);
                update(object);
            }
        }

        @Override
        public void error(String error) {

        }
    }).get(51,"parent");

}

public void selectCountry(final TagModel country){
    TagStore.getInstance().subscribe(new StoreObserver<TagSearchList>() {
        @Override
        public void update(TagSearchList object) {
            mSelectedCountryProvinceList.setValue(object.toList());
        }

        @Override
        public void update(int id, TagSearchList object) {
            if (id == country.getId()){
                TagStore.getInstance().unSubcribe(this);
                update(object);
            }
        }

        @Override
        public void error(String error) {

        }
    }).get(country.getId(),"parent");
}

public LiveData<ArrayList<TagModel>> getCountries(){
    return mCountries;
}

public LiveData<ArrayList<TagModel>> getDistances(){
    return mDistanceList;
}

public LiveData<ArrayList<TagModel>> getProvinces(){
    return mSelectedCountryProvinceList;
}

}

3 个答案:

答案 0 :(得分:5)

  

我正在使用Room Persistence库

     

以下是我使用MVVM的recyclerview适配器的代码

您可以看到CartViewModel,并且我已经将其初始化为构造函数。

构造函数从活动中获取上下文,并且

  

我已将其转换为(FragmentActivity)

private CartViewModel cartViewModel;

public CartListAdapter(Context context, List<CartModel> cartModels) {
        this.context = context;
        this.cartModels = cartModels;

        cartViewModel = ViewModelProviders.of((FragmentActivity) context).get(CartViewModel.class);
    }

这是我完整的适配器类...我希望它将对您有帮助...

public class CartListAdapter extends RecyclerView.Adapter<CartListAdapter.CartListViewHolder> {

private static final String TAG = "CartListAdapter";

private Context context;
private List<CartModel> cartModels;

private Double totalQuantity = 0.0;

private CartViewModel cartViewModel;

public CartListAdapter(Context context, List<CartModel> cartModels) {
    this.context = context;
    this.cartModels = cartModels;

    cartViewModel = ViewModelProviders.of((FragmentActivity) context).get(CartViewModel.class);
}

@NonNull
@Override
public CartListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new CartListViewHolder(LayoutInflater.from(context).inflate(R.layout.list_all_cart_item,parent,false));
}

@Override
public void onBindViewHolder(@NonNull CartListViewHolder holder, int position) {

    CartModel cartModel = cartModels.get(position);

    Glide.with(context)
            .load(cartModel.getPPICLocate())
            .into(holder.cartItemImage);

    holder.tvCartProductName.setText(cartModel.getProductName());
    holder.tvCartProductCategory.setText(cartModel.getPCategorySubID());
    holder.tvCartProductPrice.setText(cartModel.getPPriceSales());
    holder.etCartProductQuantity.setText(cartModel.getPQuantity());

    holder.btnCartPQtIncrease.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            totalQuantity = Double.valueOf(holder.etCartProductQuantity.getText().toString());
            totalQuantity = totalQuantity+1;
            cartModel.setPQuantity(totalQuantity.toString());
            updateCart(cartModel);
        }
    });

    holder.btnCartPQtDecrease.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            totalQuantity = Double.valueOf(holder.etCartProductQuantity.getText().toString());
            totalQuantity = totalQuantity-1;
            cartModel.setPQuantity(totalQuantity.toString());
            updateCart(cartModel);


        }
    });
}



@Override
public int getItemCount() {
    return cartModels.size();
}

public class CartListViewHolder extends RecyclerView.ViewHolder{

    private ImageView cartItemImage;
    private TextView tvCartProductName,tvCartProductCategory,tvCartProductPrice,
            etCartProductQuantity,tvCartProductPrevPrice;
    private ImageButton btnCartPQtIncrease,btnCartPQtDecrease;

    public CartListViewHolder(@NonNull View itemView) {
        super(itemView);

        cartItemImage= itemView.findViewById(R.id.cartItemImage);
        tvCartProductName= itemView.findViewById(R.id.tvCartProductName);
        tvCartProductCategory= itemView.findViewById(R.id.tvCartProductCategory);
        tvCartProductPrice= itemView.findViewById(R.id.tvCartProductPrice);
        etCartProductQuantity= itemView.findViewById(R.id.etCartProductQuantity);
        tvCartProductPrevPrice= itemView.findViewById(R.id.tvCartProductPrevPrice);
        btnCartPQtIncrease= itemView.findViewById(R.id.btnCartPQtIncrease);
        btnCartPQtDecrease= itemView.findViewById(R.id.btnCartPQtDecrease);

    }
}

public void addItems(List<CartModel> cartModels) {
    this.cartModels = cartModels;
    notifyDataSetChanged();
}

private void updateCart(CartModel cartModel){
    String tqt = String.valueOf(cartModel.getPQuantity());
    Log.d(TAG, "updateQuantity: "+tqt);
    /*cartRepository.updateCartRepo(cartModel);*/
    cartViewModel.updateCartItemVM(cartModel);

}

}

答案 1 :(得分:2)

您可以改为创建OnClickListener接口,然后在您可以访问视图模型的片段或活动中实现onClick方法(在接口中定义)。

答案 2 :(得分:-2)

我对此问题的解决方案是;

  • 为布局(片段或活动布局)创建一个新变量(ViewModel)
  • 在您的活动或片段中,使用ViewModelProviders
  • 获取viewModel的实例
  • 保存在MutableLiveData中填充您的recyclerView的数据并观察它并用您观察到的值填充recyclerView的适配器

这里你要注意不要在observe方法中创建适配器实例。 如果你在observe方法中创建它,它将导致泄漏