如何在RecyclerView Adapter中使用架构组件ViewModel? [英] how to use Architecture Components ViewModel inside RecyclerView Adapter?

查看:2016
本文介绍了如何在RecyclerView Adapter中使用架构组件ViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个ViewHolders,它们在垂直的RecyclerView中作为单独的视图工作.我正在使用新的架构组件ViewModel进行练习.

I have multiple ViewHolders that work as separated views inside a vertical RecyclerView. I'm practicing with the new Architecture Components ViewModel.

在ViewModel内部,我有几个想要观察的MutableLiveData列表,但是我该如何调用

Inside my ViewModel I have a couple of MutableLiveData lists that i want to observe, but how can I call

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

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

            }
        });

是否不泄漏活动或将活动保存在适配器中?

without leaking the activity or save the activity inside the adapter?

我的ViewModel

my 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;
}

推荐答案

我正在使用Room Persistence库.下面是我使用MVVM的recyclerview适配器的代码.

I am using Room Persistence library. Below is my code for recyclerview adapter using MVVM.

您可以看到CartViewModel,并且已经将其初始化为构造函数.构造函数从活动中获取上下文,我已将其转换为FragmentActivity.

You can see CartViewModel and I have initialized it into the constructor. The constructor gets the context from the activity, and I have cast it into 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);
    }

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

Here is my full adapter class. I hope it will help.

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);

}

}

这篇关于如何在RecyclerView Adapter中使用架构组件ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆