当前位置:   article > 正文

Android基于ViewBinding实现通用Adapter基类_android viewbinding for adapter

android viewbinding for adapter

首先是BaseAdapter,泛型里面传入数据类型和ViewBinding

  1. public abstract class BaseAdapter<T,V extends ViewBinding> extends RecyclerView.Adapter<BaseHolder> {
  2. private List<T> data;
  3. public BaseAdapter(List<T> data) {
  4. this.data = data;
  5. }
  6. @NonNull
  7. @Override
  8. public BaseHolder<V> onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
  9. return new BaseHolder(onBindingView(viewGroup));
  10. }
  11. @Override
  12. public void onBindViewHolder(@NonNull BaseHolder holder, int position) {
  13. onBindingData(holder,data.get(position),position);
  14. }
  15. protected abstract void onBindingData(BaseHolder<V> holder, T t, int position);
  16. protected abstract V onBindingView(ViewGroup viewGroup);
  17. @Override
  18. public int getItemCount() {
  19. return data==null?0:data.size();
  20. }
  21. }

BaseHolder

  1. public class BaseHolder<V extends ViewBinding> extends RecyclerView.ViewHolder {
  2. private V viewBinding;
  3. public BaseHolder(V viewBinding) {
  4. super(viewBinding.getRoot());
  5. this.viewBinding = viewBinding;
  6. }
  7. public V getViewBinding() {
  8. return viewBinding;
  9. }
  10. }

 之后在使用Adapter的时候,将item的ViewBinding填好后,可以直接操控item的控件,赋值,或者加载图片,所有简单的recycleview都可以直接通用,设计非常的银杏,十分好用

  1. BaseAdapter<String, ItemDeviceBinding> adapter = new BaseAdapter<String, ItemDeviceBinding>(aa) {
  2. @Override
  3. protected void onBindingData(BaseHolder<ItemDeviceBinding> holder, String s, int position) {
  4. holder.getViewBinding().tvName.setText("123");
  5. }
  6. @Override
  7. protected ItemDeviceBinding onBindingView(ViewGroup viewGroup) {
  8. ItemDeviceBinding viewBinding = ItemDeviceBinding.inflate(LayoutInflater.from(viewGroup.getContext()), viewGroup, false);
  9. return viewBinding;
  10. }
  11. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/83730
推荐阅读
相关标签
  

闽ICP备14008679号