CymChad / BaseRecyclerViewAdapterHelper

BRVAH:Powerful and flexible RecyclerAdapter
http://www.recyclerview.org/
MIT License
24.34k stars 5.16k forks source link

关于DatabindingAdatper统一基类的进一步封装 #3806

Open Theoneee opened 1 year ago

Theoneee commented 1 year ago

基类封装

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() {}

基类再次精简

    /**
     * 如果没有其他业务需求,这个方法都可以不重写
     * @param binding
     */
    @Override
    protected void bindingParams(ItemMovieBinding binding) {
        binding.setPresenter(mPresenter);
    }
zhanghehe commented 1 year ago

mark