不用再写RecyclerView的Adapter了,一个Adapter搞定
* 这可能是一个重复的轮子,仅供参考*
在以往的Android开发中,遇到列表,都要用到RecyclerView,这是谷歌所提倡的用来代替ListView的控件。相比ListView要更灵活,自由度更大,比如在做表格分割线的时候,就比Listview好用多了。
但是在使用RecyclerView的Adapter的时候,必须返回一个ViewHolder,类似于ListView的BaseAdapter中的getView方法。而且要根据不同的ViewType返回不同的ViewHolder,才能在一个RecyclerView中显示几个样式的数据。
为了解决这个问题,我采用了一种Model与ViewHolder直接绑定的方式去做,再也不用写Adapter了。
先上源码,Github地址:https://github.com/boybeak/DelegateAdapter
在gradle中使用这个库:
compile 'com.github.boybeak:adapter:1.0'
在github的readme中有使用方法,具体使用可以到github上去阅读。
核心类有哪些
几个核心的类:DelegateAdapter,AnnotationDelegate,AbsViewHolder,LayoutImpl。
DelegateAdapter 这就是那个万能的Adapter类。
AnnotationDelegate 最好使用这个类来包裹数据,再将包裹后的数据添加到DelegateAdapter中。
AbsViewHolder 所有的ViewHolder必须继承这个类,并且在这个类中进行数据事件绑定。
LayoutImpl 所有是数据必须都实现该接口,因为DelegateAdapter只接受实现了该接口的类作为数据来源。该接口有两个方法:1.getLayout,用来返回 一个Layout resourece ID。2.getHolderClass, 用来返回一个Class
基本使用方法
完整的使用方法请参考文章开头的github地址,其中有一些更加方便的做法。这里只介绍通用的便利的做法。
假如我们有这样一个model
public class User {
public long id;
public String name;
}
为了避免数据污染,我们可以做一个Delegate类,来包裹这个User
@DelegateInfo(layoutId = R.layout.xxx, holderClass = UserHolder.class)
public class UserDelegate extends AnnotationDelegate<User> {
public UserDelegate (User user) {
super(user);
}
}
之所以要这么做,是为了保护user数据,比如说列表的选中状态,就不应该存在User中,我们可以在UserDelegate中进行记录。
另外就是UserHolder类
public class UserHolder extends AbsViewHolder<UserDelegate> {
@Override
public void onBindView(Context context, UserDelegate userDelegate, int position, DelegateAdapter adapter) {
//进行数据绑定和事件绑定
}
}
DelegateAdapter应该这样使用
DelegateAdapter adapter = new DelegateAdapter (context);
adapter.add (new UserDelegate(user));
adapter.notifyDateSetChanged();
这样下来,数据就可以显示了,不需要再自定义Adapter了。
这其中的关键就是在UserDelegate中的注解@DelegateInfo中了,在这个注解中,指定了使用的布局文件和ViewHolder。
下面就是贴出读取这其中布局的代码: