经过Android让多类型Adapter从此变的简单,虽然在代码层面上减少了adapter的代码,但是在使用的时候还是会遇到一些比较尴尬的问题,比如,现在需要加一个加载更多的item在最后。所以,adapter中的itemType并不是全部依赖于bean的,并且按照之前的方式会对bean有一定的耦合,我们不应该让bean在去实现什么接口,只想单纯的bean而已,所以基于以上两点,进行改进。
我们需要从新定义ICell接口,代码如下:
public interface ICell<T> {
boolean isCurType(int position, List<T> mDatas,SmartAdapter adapter);
@LayoutRes int getLayoutId();
void onBindViewHolder(ViewHolder holder, int position,List<T> mDatas,SmartAdapter adapter);
}
其中isCurType方法用来根据条件判断是否是该类型,如果是,通过调用getLayoutId返回该类型布局文件id。
再看SmartAdapter代码:
public class SmartAdapter extends RecyclerView.Adapter<ViewHolder> {
protected List<?> mDatas;
private List<ICell<?>> itemTypes;
public SmartAdapter(@NonNull List<?> datas){
mDatas = datas;
itemTypes=new ArrayList<>();
}
public SmartAdapter regist(ICell<?> bindcell){
itemTypes.add(bindcell);
return this;
}
public List<?> getDatas(){
return mDatas;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return ViewHolder.getHolder(parent.getContext(),viewType,parent);
}
@Override
public int getItemViewType(int position) {
if (itemTypes.size()==0){
throw new RuntimeException("can not find view type ,please call regist before setAdater");
}else{
for (ICell cell:itemTypes) {
if (cell.isCurType(position,mDatas,this)){
return cell.getLayoutId();
}
}
throw new RuntimeException("can not find view type");
}
}
@Override
public int getItemCount() {
return mDatas.size();
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
for (ICell cell:itemTypes) {
if (cell.isCurType(position,mDatas,this)){
cell.onBindViewHolder(holder,position,mDatas,this);
}
}
}
}
相信已经一目了然了吧,可能有人会说为什么isCurType方法不将当前位置的数据传入,我想说的是,还是从最开始的那两个痛点出发的,因为不是所有的位置都依赖于当前数据,有时候我就希望某一个位置的条目只显示一个特定的view,跟数据无关,所以我们不能依赖当前位置的数据。
下面是具体使用方法:
rv_list.setAdapter(new SmartAdapter(datas) {
@Override
public int getItemCount() {
return datas.size() + 1;
}
}.regist(new TypeOneCell())
.regist(new TypeTwoCell())
.regist(new LoadMoreCell()));
由于添加了加载更多的条目,所以需要重写getItemcount方法;从此以后我只需要实现对应的ICell接口就好了,当然也有大神封装的更好,但是本人本着代码最少,简单的原则,没有过度封装,想更深度封装,就需要你们的聪明的大脑啦。