骚年,如果你还在用ListView赶紧换RecyclerView吧,用了之后你会发现从此你再也不想用ListView了。下面我说说两者的优缺点,listView简单易用,google工程师已经把很多功能封装好了,比如点击事件,分割线,头部,尾部。缺点:性能差,可拓展性不好。RecyclerView用法稍微复杂。但是功能强大,可拓展性好。依靠LayoutManager(通俗叫法布局管理器)可以实现多种效果,比如listview,graidview,以及瀑布流效果。并且可以设置动画,点击效果那叫一个狂拽酷炫啊。Google工程师呢也是留下了很多东西让开发者自己去发挥。条目点击我们得自己写,最恶心的是分割线和grid形式的间距设置有点恶心。还有一点我发现对于api22以上(开发时的编译版本)和api22以下是有差异的。比如我要设置recyclerview高度为wrap_content,但是视图并没有包裹而是占了一个页面。解决方式是写一个可包裹的L爱有天Mannager。对于api22以上不需要考虑,可以正常设置。这点算一个版本bug吧。那么无论listview还是recyclerview最重要的就是适配器了。终于讲到正题了。那么下面我们来聊聊Adapter
适配器其实就是把数据适配成view。通俗点说就像是一个模具,你把料(数据)放进来,我们倒个模出来。平时开发中这个列表需求是很多的,那么意味着我们要用很多次这种控件。每次用我们又得写适配器。是不是很烦,一大堆相同代码。写得手疼,于是想着要把这些相同的代码是不是可以做个封装,我们只需要把布局,把数据这些不同业务提供给外面实现。基于这个想法,有了今天我们要讲的这个主题。
业务需求1.普通常见列表。不包含头尾。要求只给一个布局,一些数据可以实现需求。
分析:数据写死肯定是不行的,这里采用泛型设计。数据设置我们可以写一个set方法设置。布局得抽象出去实现,还有数据和view之间的绑定也得抽象出去。holder也需要根据布局来重新写。
适配器代码如下:
public abstract class BaseRecyclerViewAdapter extends RecyclerView.Adapter {
protected Context mContext;
protected final LayoutInflater inflater;
protected List mDatas;
protected int mLayoutId;
private OnItemClickListener onItemClickListener;
public BaseRecyclerViewAdapter(Context mContext, int layoutId, List datas) {
this.mContext = mContext;
this.mLayoutId = layoutId;
this.mDatas = datas;
inflater = LayoutInflater.from(mContext);
}
/*数据操作*/
public void addData(T bean) {
mDatas.add(bean);
notifyDataSetChanged();
}
public void addDatas(List datas) {
mDatas.addAll(datas);
notifyDataSetChanged();
}
public void remove(int index) {
if (index < 0 && index > mDatas.size()) {
throw new IndexOutOfBoundsException("index not right");
}
else mDatas.remove(index);
notifyDataSetChanged();
}
public void removeAll() {
mDatas.clear();
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(mLayoutId, parent, false);
return onCreatHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final int pos = getRealPosition(holder);
final T bean = mDatas.get(pos);
onBindHolder(holder, pos, bean);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(pos, bean);
}
}
});
}
private int getRealPosition(RecyclerView.ViewHolder holder) {
return holder.getLayoutPosition();
}
@Override
public int getItemCount() {
return mDatas == null ? 0 : mDatas.size();
}
/*写一个接口回调点击事件*/
public interface OnItemClickListener {
void onItemClick(int position, T bean);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
/**
* @param view
* @return 抽象出去
*/
public abstract RecyclerView.ViewHolder onCreatHolder(View view);
protected abstract void onBindHolder(RecyclerView.ViewHolder holder, int pos, T bean);
}
2.使用过程中发现ViewHolder以及查找id并不好用,把上面的适配器升级一下,我们来一个BaseViewHolder把一些数据装配操作也封装起来。BaseViewHolder封装了一些常用控件的数据操作,事件监听等。基于这些想法,我们再做升级改造。
public abstract class BaseRecyclerAdapter extends RecyclerView.Adapter {
protected Context mContext;
protected List mDatas;
private int totalList;
private int itemLayoutId;
private OnItemClickListener onItemClickListener;
private OnItemLongClickListener onItemLongClickListener;
private final LayoutInflater mInflater;
private static final int TYPE_HEAD = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOT = 2;
private boolean isScrolling = true; //false表示滑动,true表示不滑动
private View headerView, footerView; //头和尾的view
public BaseRecyclerAdapter(Context ctx, int itemLayoutId, List list) {
this.mContext = ctx;
this.itemLayoutId = itemLayoutId;
mDatas = (list != null) ? list : new ArrayList();
mInflater = LayoutInflater.from(ctx);
}
/*数据操作*/
public void addData(T bean) {
mDatas.add(bean);
notifyDataSetChanged();
}
public void addDatas(List datas) {
mDatas.addAll(datas);
notifyDataSetChanged();
}
public void remove(int index) {
if (index < 0 && index > mDatas.size()) {
throw new IndexOutOfBoundsException("index not right");
}
else mDatas.remove(index);
notifyDataSetChanged();
}
public void removeAll() {
mDatas.clear();
notifyDataSetChanged();
}
public void setFooterView(View view) {
this.footerView = view;
}
public void setHeaderView(View view) {
this.headerView = view;
}
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEAD && headerView != null) {
return new BaseViewHolder(mContext, headerView);
}
if (viewType == TYPE_FOOT && footerView != null) {
return new BaseViewHolder(mContext, footerView);
}
View view = mInflater.inflate(itemLayoutId, parent, false);
return new BaseViewHolder(mContext, view);
}
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
if (getItemViewType(position) != TYPE_ITEM) {
//如果不是正常的Item,就不去绑定数据
return;
}
final int p = getRealPosition(position);
convert(holder, p, mDatas.get(p));
if (onItemClickListener != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onItemClickListener.onItemClick(p, mDatas.get(p));
}
});
}
if (onItemLongClickListener != null) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
onItemLongClickListener.onLongItemClick(p, mDatas.get(p));
return true;
}
});
}
}
private int getRealPosition(int position) {
return headerView == null ? position : position - 1;
}
@Override
public int getItemCount() {
if (mDatas == null) {
return 0;
}
if (headerView != null && footerView != null) {
//头尾都不为空
totalList = mDatas.size() + 2;
} else if (headerView == null && footerView == null) {
//头尾都为空
totalList = mDatas.size();
} else {
//头尾有一个不为空
totalList = mDatas.size() + 1;
}
return totalList;
}
@Override
public int getItemViewType(int position) {
if (position == 0 && headerView != null) {
return TYPE_HEAD;
} else if (position + 1 == getItemCount() && footerView != null) {
return TYPE_FOOT;
} else {
return TYPE_ITEM;
}
}
/*
* 需要根据实际情况设置的部分抽象出去
* */
protected abstract void convert(BaseViewHolder holder, int p, T t);
/*接口回调点击和长按事件*/
public interface OnItemClickListener {
void onItemClick(int position, T bean);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemLongClickListener {
void onLongItemClick(int position, T bean);
}
public void setOnItemLongClickListener(OnItemLongClickListener onLongClickListener) {
this.onItemLongClickListener = onLongClickListener;
}
}
BaseViewHolder的代码如下
public class BaseViewHolder extends RecyclerView.ViewHolder {
/*
* 数据量不大,最好在千级以内
* key必须为int类型,这中情况下的HashMap可以用SparseArray代替:比如
* HashMap map = new HashMap<>();
* 用SparseArray代替:
* SparseArray
3.使用中发现对于GridLayout,瀑布流这种会导致头部和尾部变成其中的item。这显然不是我们想要的。那么就对着两种情况特殊处理。
怎么做呢?在adapter中重写onAttachedToRecyclerView
但是这种做法无法解决瀑布流的问题,对于StaggeredGridLayoutManager我们需要重写onViewAttachedToWindow
/**
* @param recyclerView 处理GridLayoutManager
*/
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof GridLayoutManager) {
final GridLayoutManager gridLayoutManager = (GridLayoutManager) manager;
//setSpanSizeLookup的getSpanSize可以控制列数
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return (getItemViewType(position) == TYPE_HEAD || getItemViewType(position) == TYPE_FOOT) ? gridLayoutManager.getSpanCount() : 1;
}
});
}/*else if (manager instanceof StaggeredGridLayoutManager) { StaggeredGridLayoutManager并没有setSpanSizeLookup这个方法,所以此路不通
StaggeredGridLayoutManager staggeredManager = (StaggeredGridLayoutManager) manager;
}*/
}
/**
* @param holder
* 处理StaggerdGridLayoutManager
*/
@Override
public void onViewAttachedToWindow(BaseViewHolder holder) {
super.onViewAttachedToWindow(holder);
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp != null && lp instanceof StaggeredGridLayoutManager.LayoutParams) {
StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
if (headerView != null && holder.getLayoutPosition() == 0) {
p.setFullSpan(true);
}
if (footerView != null && holder.getLayoutPosition() == getItemCount() - 1) {
p.setFullSpan(true);
}
}
}
至此,我们的目的就达到了,使用起来超简单可以继承BaseRecyclerAdapter,也可以直接用它的匿名内部类。这里就不赘述了。使用本类可以减少你Adapter百分之70的代码,赶紧拿去撸吧!