Java版本
public abstract class BaseRecyclerViewAdapterJava<T,VH extends BaseRecyclerViewAdapterJava.ViewHolderJava<T>> extends RecyclerView.Adapter<VH> {
private LayoutInflater inflater;
private List<T> items;
public BaseRecyclerViewAdapterJava(Context context) {
this.inflater = LayoutInflater.from(context);
}
@NonNull @Override public abstract VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType);
@Override public void onBindViewHolder(@NonNull VH holder, int position) {
holder.bindView(items.get(position));
}
@Override public int getItemCount() {
return items.size();
}
// 子类继承这个方法实现不同Item的布局即可
abstract int getLayoutId();
public static abstract class ViewHolderJava<T> extends RecyclerView.ViewHolder{
public ViewHolderJava(@NonNull View itemView) {
super(itemView);
}
// 绑定Item Data和View
abstract void bindView(T t);
}
}
Kotlin版本
abstract class BaseRecyclerViewAdapter<T, VH : BaseRecyclerViewAdapter.BaseViewHolder<T>>(context: Context, items: List<T>) : RecyclerView.Adapter<VH>() {
private val items = items
private val inflater: LayoutInflater by lazy {
LayoutInflater.from(context)
}
abstract override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH
override fun getItemCount(): Int{
return items.size
}
override fun onBindViewHolder(holder: VH, position: Int){
holder.bindView(items[position])
}
abstract fun getLayoutId(): Int
abstract class BaseViewHolder<T>(itemView: View) : RecyclerView.ViewHolder(itemView) {
abstract fun bindView(t: T)
}
}
总结:
我没有把点击监听加进去,保证了Adapter
功能最精简,加进去也很简单,可以在继承BaseViewHolder
的bind
方法里实现,也可以在Adapter
里增加一个内部接口来实现。