abstract class BaseDataBindingAdapter<T, DB : ViewDataBinding> :
BaseQuickAdapter<T, DataBindingHolder<DB>>() {
override fun onCreateViewHolder(
context: Context,
parent: ViewGroup,
viewType: Int
): DataBindingHolder<DB> {
val clazz = this.getClazz<Class<DB>>(1)
val mBinding = clazz.getDeclaredMethod(
"inflate",
LayoutInflater::class.java,
ViewGroup::class.java,
Boolean::class.java
).invoke(null, LayoutInflater.from(parent.context), parent, false) as DB
return DataBindingHolder(mBinding)
}
override fun onBindViewHolder(holder: DataBindingHolder<DB>, position: Int, item: T?) {
item?.let {
holder.binding.run {
bindingParams(item)
executePendingBindings()
}
}
}
protected open fun DB.bindingParams(item:T?) {}
}
/**
* 获取当前类绑定的泛型clazz
* @param index 泛型所处index
*/
fun <T> Any.getClazz(index: Int = 0): T {
return (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[index] as T
}
子类使用
public class DataBindingAdapter extends BaseDataBindingAdapter<Movie, ItemMovieBinding> {
private final MoviePresenter mPresenter = new MoviePresenter();
@Override
protected void bindingParams(ItemMovieBinding binding, @Nullable Movie item) {
binding.setMovie(item);
binding.setPresenter(mPresenter);
}
}
由于item是必须的,所以我们完全也可以将其规定命名后放置在基类
override fun onBindViewHolder(holder: DataBindingHolder<DB>, position: Int, item: T?) {
item?.let {
holder.binding.run {
// 规定名称
setVariable(BR.item,item)
bindingParams()
executePendingBindings()
}
}
}
protected open fun DB.bindingParams() {}
基类封装
子类使用
由于item是必须的,所以我们完全也可以将其规定命名后放置在基类
基类再次精简