RecyclerView 添加Header和fooder
谷歌发布了一个RecyclerView 来代替ListView,然而RecyclerView 并没有ListView header 和 footer.为什么会没有呢,谷歌坑我们??显然不是。
其实ListView 也是“没有”这个功能,我们看看ListView中setAdapter 的代码片段
public void setAdapter(ListAdapter adapter) {
....
if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
mAdapter = new HeaderViewListAdapter(mHeaderViewInfos, mFooterViewInfos, adapter);
} else {
mAdapter = adapter;
}
...
}
我们可以看setAdapter 对是否有headerView 进行了判断,如果有headviewer的话就会对adapter 进行二次封装,所以这就是为什么我说ListView 其实是没有header和footer,这也是为什么设置了adapter之后添加header会出错的问题了,因为adapter是不一样的
既然知道了ListView 是怎么构造头尾部的,我们也可以用同样的办法给Recyclerview 构造一个
因为我使用footer 的原因是要构造一个更多加载,所以我将已构造一个更多加载为示例
**
* Created With Android Studio
* User 47
* Date 15/5/12
* Time 上午10:07
* 一个Load Adapter
*/
private class MoreAdapter extends Adapter<ViewHolder> {
public static final int LAST_ITEM_TYPE = -2333333;
private Adapter mAdapter;
private AdapterDataObserver observer = new AdapterDataObserver() {
MoreAdapter moreAdapter = MoreAdapter.this;
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
moreAdapter.notifyItemRangeChanged(positionStart,itemCount);
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
moreAdapter.notifyItemRangeInserted(positionStart,itemCount);
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
moreAdapter.notifyItemRangeRemoved(positionStart,itemCount);
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
moreAdapter.notifyItemMoved(fromPosition,itemCount);
}
};
public void setWrapAdapter(Adapter adapter){
if(adapter == null) return;
if(mAdapter != null) mAdapter.unregisterAdapterDataObserver(observer);
mAdapter = adapter;
mAdapter.registerAdapterDataObserver(observer);
}
public Adapter getWrapAdapter(){
return mAdapter;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == LAST_ITEM_TYPE)
return mMoreViewHolder;
return onRealCreateViewHolder(parent, viewType);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position == getRealItemCount()) {
return;
}
onRealBindViewHolder(holder, position);
}
@Override
public int getItemViewType(int position) {
if(position == getRealItemCount()) return LAST_ITEM_TYPE;
return mAdapter.getItemViewType(position);
}
其实整个代码很简单,就是自己封装一个Adapter,然后可以把Adapter放到里面去,让它注册自己的数据观察者,以便到时候可以通知刷新