gpt4 book ai didi

Android 架构组件 : using ViewModel for RecyclerView items

转载 作者:IT老高 更新时间:2023-10-28 22:18:29 25 4
gpt4 key购买 nike

我正在试验架构组件,我想为 RecyclerView 的每个项目构建一个 ViewModel。我不确定这在形式上是否正确,或者我应该坚持“旧方式”。

我有这个适配器:

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {

private List<Post> list;
public static class PostViewHolder extends RecyclerView.ViewHolder{
final ItemPostBinding binding;

public PostViewHolder(ItemPostBinding binding){
super(binding.getRoot());
this.binding = binding;
}
}

@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemPostBinding binding = DataBindingUtil
.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_post,
parent, false);


return new PostViewHolder(binding, parent.getContext());
}

@Override
public void onBindViewHolder(PostViewHolder holder, int position) {
holder.binding.setPost(list.get(position));
holder.binding.executePendingBindings();
}

@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}

public void setList(List<Post> list){
this.list = list;
notifyDataSetChanged();
}
}

效果很好,但它非常基本。如何更新它,以便每个项目都有自己的 ViewModel 关联?这有可能吗?

编辑:玩它,我尝试通过以下方式放入 ViewModel:

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {

private List<Post> list;
public static class PostViewHolder extends RecyclerView.ViewHolder{
final ItemPostBinding binding;
private final Context context;
private GalleryItemViewModel viewModel;

public PostViewHolder(ItemPostBinding binding, Context context){
super(binding.getRoot());
this.binding = binding;
this.context = context;
}

public Context getContext(){
return context;
}

public void setViewModel(GalleryItemViewModel viewModel){
this.viewModel = viewModel;
binding.setViewModel(viewModel);
}
}

@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemPostBinding binding = DataBindingUtil
.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_post,
parent, false);


return new PostViewHolder(binding, parent.getContext());
}

@Override
public void onBindViewHolder(PostViewHolder holder, int position) {
GalleryItemViewModel vm = ViewModelProviders.of((FragmentActivity) holder.getContext()).get(GalleryItemViewModel.class);
vm.setPost(list.get(position));
holder.setViewModel(vm);
}

@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}

public void setList(List<Post> list){
this.list = list;
notifyDataSetChanged();
}
}

它有效,但这是正确的方法吗?

最佳答案

有趣,但回答 - 这是正确的方式,应该被接受:)您可以进行一些代码清理并从 PostViewHolder 中删除 GalleryItemViewModel,因为您正在创建硬引用而不是使用它。然后直接在 onBindViewHolder() 中像 holder.binding.setViewModel(vm);

一样使用它

这是 link MVVM 代码示例可以帮助您。

关于Android 架构组件 : using ViewModel for RecyclerView items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com