java 如何在 RecyclerView Adapter 中使用架构组件 ViewModel?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44495323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:12:21  来源:igfitidea点击:

how to use Architecture Components ViewModel inside RecyclerView Adapter?

javaandroidandroid-architecture-components

提问by quantum apps

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

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

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

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

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

and

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?

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

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

回答by Wasi Sadman

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

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

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.

您可以看到 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);
    }

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

}

}

回答by Enes

My solution to this issue is;

我对这个问题的解决方案是;

  • create a new variable(ViewModel) for the layout (fragment or activity layout)
  • in your activity or fragment get the instance of your viewModel with ViewModelProviders
  • hold the data which fills your recyclerView in MutableLiveData and observe it and fill the adapter of recyclerView with the value you observed
  • 为布局(片段或活动布局)创建一个新变量(ViewModel)
  • 在您的活动或片段中获取您的 viewModel 的实例 ViewModelProviders
  • 在 MutableLiveData 中保存填充您的 recyclerView 的数据并观察它并用您观察到的值填充 recyclerView 的适配器

here you mut be careful not to create adapter instance in observe method. if you create it in observe method, it will make leaks

在这里你必须小心不要在observe 方法中创建适配器实例。如果你在observe方法中创建它,它会泄漏