ViewBinding 和 RecycleView 结合使用,废话不多说,直接上代码
首先本人使用的是 第三方库 的baseAdapter :
com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.6
第一步,我们新建一个BaseViewBindingAdapter 基类
/**
* @author Create by 17474 on 2021/4/29.
* Email: [email protected]
* Describe:使用ViewBinding 封装
* 使用泛型 VH 指定类型为 BaseViewHolder
*/
public abstract class BaseViewBindingAdapter<T, VH extends BaseViewHolder> extends BaseQuickAdapter<T, VH> {
public BaseViewBindingAdapter(int layoutResId, @Nullable List<T> data) {
super(layoutResId, data);
}
public BaseViewBindingAdapter(int layoutResId) {
super(layoutResId);
}
@NotNull
@Override
protected VH onCreateDefViewHolder(@NotNull ViewGroup parent, int viewType) {
return getViewBinding(viewType,LayoutInflater.from(getContext()),parent);
}
protected abstract VH getViewBinding(int viewType, LayoutInflater from, ViewGroup parent);
}
第二步,我们创建BaseViewBindingHolder
/**
* @author Create by 17474 on 2021/4/29.
* Email: [email protected]
* Describe:
*/
public class BaseViewBindingHolder <VB extends ViewBinding> extends BaseViewHolder {
public VB viewBind;
public BaseViewBindingHolder(VB viewBind) {
super(viewBind.getRoot());
this.viewBind = viewBind;
}
public VB getViewBind() {
return viewBind;
}
}
第三步 创建一个 adapter_home_post_item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/middle_layout_margin_default"
app:cardBackgroundColor="@color/layout_bg"
app:cardCornerRadius="@dimen/layout_corner_default"
app:cardElevation="@dimen/layout_elevation_default">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">