ViewHolder 的概念在 ListView 的年代已有,到了 RecyclerView,Google 给了名份。
人如其名,名字与构造函数都体现了其必须跟 View 绑定,呈一一对应关系。

有了ViewHolder,只代表列表中的其中一项。要展示整个列表,那么则需 RecyclerView.Adapter

RecyclerView.Adapter 里最需要关注的就是截图的几个方法。getItemCount()没什么好说的,其他的方法简单介绍如下:

一些伪代码,就这样,整个列表就完成了。
如果要再搞一个列表。又要这么重复一遍。
所以,安利下 https://github.com/hongyangAndroid/baseAdapter
主类 MultiItemTypeAdapter(多种viewType时使用) 继承了 RecyclerView.Adapter。将需要重写的方法交给 ItemViewDelegateManager 处理。通过 viewType 获取到指定的 ItemViewDelegate。

ItemViewDelegate 是一个接口,提供了三个接口。

使用过程中,如果要对某种数据呈现某种布局时,便可直接实现该接口。至于 ViewHolder 其内部已有实现。主要是做了一些简单的通用封装。其在接入过程中,不需再新增 ViewHolder。如下图所示。

最后,将这个ItemViewDelegate 添加到 MultiItemTypeAdapter 就可以了。

一种 ViewType情况呢?直接用CommonAdapter 即可。其内部实现也是集成MultiItemTypeAdapter,只添加了一个 ItemViewDelegate 罢了。

总结,优点:不用再写 RecyclerView.Adapter 了,也不用再写 ViewHolder 了。
网友评论