使用dataBinding 写的 RecyclerView通用适配器,支持多布局,多种bean混合使用
使用方法
CommonAdapter adapter = new CommonAdapter();
adapter.addItemType(R.layout.item_news,BR.news, News.class);
adapter.addItemType(R.layout.item_news2,BR.bean, News2.class);
package com.example.httpdemo.adapter;
import android.annotation.SuppressLint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baselibrary.util.ToastUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* time : 2021/05/11
* desc : RecyclerView通用适配器,使用dataBinding
*/
public class CommonAdapter extends RecyclerView.Adapter<CommonAdapter.MViewHoder> {
private List datas = new ArrayList<>();
/**
* 存储布局id, key为对应类型的类名
*/
private Map<String,Integer> beanLayoutIdMap = new HashMap();
/**
* 存储布局文件中的variableId, key为对应类型的类名
*/
private Map<String,Integer> beanVariableIdMap = new HashMap();
/**
* 添加布局
* @param layoutId 布局文件id
* @param variableId 布局文件中的variableId
* @param c 对应类型
*/
public void addItemType(int layoutId,int variableId,Class c){
String key = getKeyByClass(c);
beanLayoutIdMap.put(key,layoutId);
beanVariableIdMap.put(key,variableId);
}
public void addNewsList(List datas) {
int oldSize = datas.size();
if(oldSize == 0){
this.datas = datas;
notifyDataSetChanged();
return;
}
this.datas.addAll(datas);
notifyItemRangeChanged(oldSize - 1, datas.size());
}
@Override
public int getItemViewType(int position) {
Object bean = datas.get(position);
//LayoutId 作为 ItemViewType
return getLayoutIdByClass(bean.getClass());
}
@NonNull
@Override
public MViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), viewType, parent, false);
return new MViewHoder(binding);
}
@Override
public void onBindViewHolder(@NonNull MViewHoder holder, @SuppressLint("RecyclerView") int position) {
Object bean = datas.get(position);
holder.binding.setVariable(getVariableIdByClass(bean.getClass()), bean);
}
@Override
public int getItemCount() {
return datas.size();
}
class MViewHoder extends RecyclerView.ViewHolder {
public ViewDataBinding binding;
public MViewHoder(@NonNull ViewDataBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
/**
* 获取实体类对应的布局文件中的variableId
* @param c
* @return
*/
private int getVariableIdByClass(Class c){
return beanVariableIdMap.get(getKeyByClass(c));
}
/**
* 获取实体类对应的布局文件Id
* @param c
* @return
*/
private int getLayoutIdByClass(Class c){
return beanLayoutIdMap.get(getKeyByClass(c));
}
/**
* beanLayoutIdMap 和 beanVariableIdMap 使用的 key
* @param c
* @return
*/
private String getKeyByClass(Class c){
return c.getSimpleName();
}
}
法国海军