本文是MultiItem
系列的进阶文章,讲解如何利用 DataBinding
改善对MultiItem
的开发,其中RecyclerView
的Adapter
和ViewHolderManager
都不须要编写,使用库中封装的基础类就能够完成业务代码的开发,使你的RecyclerView
代码更加干净清爽。MutliItem
主要解决多类型RecyclerView Adapter问题,在正常使用中作到了Adapter
零编码,解放了复杂的Adapter
类,提升扩展性。html
Github地址:github.com/free46000/M…,请你们多多关注,更多更新会首先在GitHub上体现,也会在第一时间在本平台发布。 java
在build.gradle
开启DataBinding
:android
dataBinding {
enabled = true
}复制代码
为数据源注册ViewHolderManager
管理类:git
//初始化adapter
BaseItemAdapter adapter = new BaseItemAdapter();
//绑定写法一(简单):直接传入BR.itemData(VariableId)
adapter.register(TextBean.class, new DataBindViewHolderManager<>(R.layout.item_text_data_bind, BR.itemData));
//绑定写法二(自由):传入ItemBindView接口实例,能够定制绑定业务逻辑
adapter.register(ImageTextBean.class, new DataBindViewHolderManager<>(
R.layout.item_image_text_data_bind, this::onBindViewHolder));复制代码
上面代码中写法二的实现咱们看到了this::onBindViewHolder
这一行代码,这是使用表达式后的简写方式,就是实现了一个ItemBindView
接口的实例,onBindViewHolder
方法为接口中具体执行的方法:github
//将数据绑定的视图中,具体代码由DataBinding库自动生成
private void onBindViewHolder(ViewDataBinding dataBinding, Object data) {
//还能够写一些其余的绑定业务逻辑......
dataBinding.setVariable(BR.itemData, data);
}复制代码
经过以上简单几行代码咱们就完成了多类型的RecyclerView
列表的代码,是否是很是干净清爽,其中BaseItemAdapter
和DataBindViewHolderManager
都是MultiItem
库中封装好的基础类,能够在业务代码中直接使用。网络
这里使用了DataBinding
的BindingAdapter
注解,能够为xml
定制一些设值方法,具体使用方式你们能够参考BindingAdapter的官方文档Demo
中BindingAdapter
的定制代码:布局
/** * 经过android:imageUrl能够在xml布局中直接为ImageView设置url地址 * * @param imageView xml中ImageView实例 * @param imgUrl 网络图片地址 */
@BindingAdapter({"android:imageUrl"})
public static void setImageViewResource(ImageView imageView, String imgUrl) {
Context context = imageView.getContext();
//此处经过imgUrl字符串获取资源ID,你们可根据业务使用第三方库加载网络图片
int resID = context.getResources().getIdentifier(imgUrl, "drawable", context.getPackageName());
imageView.setImageResource(resID);
}复制代码
这样咱们就能够经过android:imageUrl
在xml
布局中直接为ImageView
设置url
地址了:post
<ImageView ... android:imageUrl="@{itemData.imgUrl}" />复制代码
Databinding
是MVVM
模式的基础,以前也写了文章咱们为何要使用DataBinding,里面经过代码的对比,总结说明为何要使用DataBinding的技术,有兴趣的同窗能够阅读一下,在这里我把文章里的一小段总结贴出来:gradle
DataBinding为数据驱动:数据变化后自动更新UI;事件处理:直接找到目标实例处理用户操做的事件。这样咱们就不须要和UI或者控件打交道,只须要在java代码中处理业务逻辑就行了,很是清晰,其他的统一交给binding库去完成。下降了代码耦合度,使得数据独立于UI,对之后程序的变化和维护都有积极的影响。ui
把Databinding
拿出来单独写了这篇文章,是但愿你们对Databinding
重视起来,随着在开发中愈来愈多的使用,你就更能体会到它所带来的好处,本文主要写了MultiItem
和DataBinding
的结合,仅涉及了一些Databinding
基础用法,可是也足以对咱们的代码结构有了很大的提高,若是你们对DataBinding
感兴趣,欢迎你们多多交流