header和footer包装器类
import android.support.v4.util.SparseArrayCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
/**
* 介绍:一个给RecyclerView添加HeaderView FooterView的装饰Adapter类
* 重点哦~ RecyclerView的HeaderView将可以被系统回收,不像老版的HeaderView是一个强引用在内存里
* 作者:zhangxutong
* 邮箱:zhangxutong@imcoming.com
* 时间: 2016/8/2.
*/
public abstract class HeaderRecyclerAndFooterWrapperAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int BASE_ITEM_TYPE_HEADER = 1000000;//headerview的viewtype基准值
private static final int BASE_ITEM_TYPE_FOOTER = 2000000;//footerView的ViewType基准值
//存放HeaderViews的layoudID和data,key是viewType,value 是 layoudID和data,
// 在createViewHOlder里根据layoutId创建UI,
// 在onbindViewHOlder里依据这个data渲染UI,同时也将layoutId回传出去用于判断何种Header
private SparseArrayCompat<SparseArrayCompat> mHeaderDatas = new SparseArrayCompat<SparseArrayCompat>();
private SparseArrayCompat<View> mFooterViews = new SparseArrayCompat<>();//存放FooterViews,key是viewType
protected RecyclerView.Adapter mInnerAdapter;//内部的的普通Adapter
public HeaderRecyclerAndFooterWrapperAdapter(RecyclerView.Adapter mInnerAdapter) {
this.mInnerAdapter = mInnerAdapter;
}
public int getHeaderViewCount() {
return mHeaderDatas.size();
}
public int getFooterViewCount() {
return mFooterViews.size();
}
private int getInnerItemCount() {
return mInnerAdapter != null ? mInnerAdapter.getItemCount() : 0;
}
/**
* 传入position 判断是否是headerview
*
* @param position
* @return
*/
public boolean isHeaderViewPos(int position) {// 举例, 2 个头,pos 0 1,true, 2+ false
return getHeaderViewCount() > position;
}
/**
* 传入postion判断是否是footerview
*
* @param position
* @return
*/
public boolean isFooterViewPos(int position) {//举例, 2个头,2个inner,pos 0 1 2 3 ,false,4+true
return position >= getHeaderViewCount() + getInnerItemCount();
}
/**
* 添加HeaderView
*
* @param layoutId headerView 的LayoutId
* @param data headerView 的data(可能多种不同类型的header 只能用Object了)
*/
public void addHeaderView(int layoutId, Object data) {
//mHeaderViews.put(mHeaderViews.size() + BASE_ITEM_TYPE_HEADER, v);
SparseArrayCompat headerContainer = new SparseArrayCompat();
headerContainer.put(layoutId, data);
mHeaderDatas.put(mHeaderDatas.size() + BASE_ITEM_TYPE_HEADER, headerContainer);
}
/**
* 设置(更新)某个layoutId的HeaderView的数据
*
* @param layoutId
* @param data
*/
public void setHeaderView(int layoutId, Object data) {
boolean isFinded = false;
for (int i = 0; i < mHeaderDatas.size(); i++) {
SparseArrayCompat sparse = mHeaderDatas.valueAt(i);
if (layoutId == sparse.keyAt(0)) {
sparse.setValueAt(0, data);
isFinded = true;
}
}
if (!isFinded) {//没发现 说明是addHeaderView
addHeaderView(layoutId, data);
}
}
/**
* 设置某个位置的HeaderView
*
* @param headerPos 从0开始,如果pos过大 就是addHeaderview
* @param layoutId
* @param data
*/
public void setHeaderView(int headerPos, int layoutId, Object data) {
if (mHeaderDatas.size() > headerPos) {
SparseArrayCompat headerContainer = new SparseArrayCompat();
headerContainer.put(layoutId, data);
mHeaderDatas.setValueAt(headerPos, headerContainer);
} else if (mHeaderDatas.size() == headerPos) {//调用addHeaderView
addHeaderView(layoutId, data);
} else {
//
addHeaderView(layoutId, data);
}
}
/**
* 添加FooterView
*
* @param v
*/
public void addFooterView(View v) {
mFooterViews.put(mFooterViews.size() + BASE_ITEM_TYPE_FOOTER, v);
}
/**
* 清空HeaderView数据
*/
public void clearHeaderView() {
mHeaderDatas.clear();
}
public void clearFooterView() {
mFooterViews.clear();
}
public void setFooterView(View v) {
clearFooterView();
addFooterView(v);
}
@Override
public int getItemViewType(int position) {
if (isHeaderViewPos(position)) {
return mHeaderDatas.keyAt(position);
} else if (isFooterViewPos(position)) {//举例:header 2, innter 2, 0123都不是,4才是,4-2-2 = 0,ok。
return mFooterViews.keyAt(position - getHeaderViewCount() - getInnerItemCount());
}
return super.getItemViewType(position - getHeaderViewCount());
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (mHeaderDatas.get(viewType) != null) {//不为空,说明是headerview
//return new ViewHolder(parent.getContext(), mHeaderViews.get(viewType));
//return createHeader(parent, mHeaderViews.indexOfKey(viewType)); 第一种方法是让子类实现这个方法 构建ViewHolder
return ViewHolder.get(parent.getContext(), null, parent, mHeaderDatas.get(viewType).keyAt(0), -1);
} else if (mFooterViews.get(viewType) != null) {//不为空,说明是footerview
return new ViewHolder(parent.getContext(), mFooterViews.get(viewType));
}
return mInnerAdapter.onCreateViewHolder(parent, viewType);
}
//protected abstract RecyclerView.ViewHolder createHeader(ViewGroup parent, int headerPos);
protected abstract void onBindHeaderHolder(ViewHolder holder, int headerPos, int layoutId, Object o);//多回传一个layoutId出去,用于判断是第几个headerview
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (isHeaderViewPos(position)) {
int layoutId = mHeaderDatas.get(getItemViewType(position)).keyAt(0);
onBindHeaderHolder((ViewHolder) holder, position, layoutId, mHeaderDatas.get(getItemViewType(position)).get(layoutId));
return;
} else if (isFooterViewPos(position)) {
return;
}
//举例子,2个header,0 1是头,2是开始,2-2 = 0
mInnerAdapter.onBindViewHolder(holder, position - getHeaderViewCount());
}
@Override
public int getItemCount() {
return getInnerItemCount() + getHeaderViewCount() + getFooterViewCount();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
mInnerAdapter.onAttachedToRecyclerView(recyclerView);
//为了兼容GridLayout
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof GridLayoutManager) {
final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
final GridLayoutManager.SpanSizeLookup spanSizeLookup = gridLayoutManager.getSpanSizeLookup();
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
int viewType = getItemViewType(position);
if (mHeaderDatas.get(viewType) != null) {
return gridLayoutManager.getSpanCount();
} else if (mFooterViews.get(viewType) != null) {
return gridLayoutManager.getSpanCount();
}
if (spanSizeLookup != null)
return spanSizeLookup.getSpanSize(position);
return 1;
}
});
gridLayoutManager.setSpanCount(gridLayoutManager.getSpanCount());
}
}
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
mInnerAdapter.onViewAttachedToWindow(holder);
int position = holder.getLayoutPosition();
if (isHeaderViewPos(position) || isFooterViewPos(position)) {
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp != null
&& lp instanceof StaggeredGridLayoutManager.LayoutParams) {
StaggeredGridLayoutManager.LayoutParams p =
(StaggeredGridLayoutManager.LayoutParams) lp;
p.setFullSpan(true);
}
}
}
}
通用ViewHolder
package mcxtzhang.itemdecorationdemo.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.util.Linkify;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AbsListView;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
/**
* 通用的RecyclerView 的ViewHolder ,使用者无需关心
* Created by zhangxutong .
* Date: 16/03/11
*/
public class ViewHolder extends RecyclerView.ViewHolder {
private SparseArray<View> mViews;
private int mPosition;
private View mConvertView;
private Context mContext;
private int mLayoutId;
public ViewHolder(Context context, View itemView, ViewGroup parent, int position) {
super(itemView);
mContext = context;
mConvertView = itemView;
mPosition = position;
mViews = new SparseArray<View>();
mConvertView.setTag(this);
}
public ViewHolder(Context context, View itemView) {
super(itemView);
mContext = context;
mConvertView = itemView;
mViews = new SparseArray<View>();
}
public static ViewHolder get(Context context, View convertView,
ViewGroup parent, int layoutId, int position) {
if (convertView == null) {
View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
false);
ViewHolder holder = new ViewHolder(context, itemView, parent, position);
holder.mLayoutId = layoutId;
return holder;
} else {
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.mPosition = position;
return holder;
}
}
/**
* 通过viewId获取控件
*
* @param viewId
* @return
*/
public <T extends View> T getView(int viewId) {
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId, view);
}
return (T) view;
}
public View getConvertView() {
return mConvertView;
}
/**
* 设置TextView的值
*
* @param viewId
* @param text
* @return
*/
public ViewHolder setText(int viewId, String text) {
TextView tv = getView(viewId);
tv.setText(text);
return this;
}
public ViewHolder setSelected(int viewId, boolean selected) {
View v = getView(viewId);
v.setSelected(selected);
return this;
}
public ViewHolder setImageResource(int viewId, int resId) {
ImageView view = getView(viewId);
view.setImageResource(resId);
return this;
}
public ViewHolder setImageBitmap(int viewId, Bitmap bitmap) {
ImageView view = getView(viewId);
view.setImageBitmap(bitmap);
return this;
}
public ViewHolder setImageDrawable(int viewId, Drawable drawable) {
ImageView view = getView(viewId);
view.setImageDrawable(drawable);
return this;
}
public ViewHolder setBackgroundColor(int viewId, int color) {
View view = getView(viewId);
view.setBackgroundColor(color);
return this;
}
public ViewHolder setBackgroundRes(int viewId, int backgroundRes) {
View view = getView(viewId);
view.setBackgroundResource(backgroundRes);
return this;
}
public ViewHolder setTextColor(int viewId, int textColor) {
TextView view = getView(viewId);
view.setTextColor(textColor);
return this;
}
public ViewHolder setTextColorRes(int viewId, int textColorRes) {
TextView view = getView(viewId);
view.setTextColor(mContext.getResources().getColor(textColorRes));
return this;
}
@SuppressLint("NewApi")
public ViewHolder setAlpha(int viewId, float value) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getView(viewId).setAlpha(value);
} else {
// Pre-honeycomb hack to set Alpha value
AlphaAnimation alpha = new AlphaAnimation(value, value);
alpha.setDuration(0);
alpha.setFillAfter(true);
getView(viewId).startAnimation(alpha);
}
return this;
}
public ViewHolder setVisible(int viewId, boolean visible) {
View view = getView(viewId);
view.setVisibility(visible ? View.VISIBLE : View.GONE);
return this;
}
public ViewHolder linkify(int viewId) {
TextView view = getView(viewId);
Linkify.addLinks(view, Linkify.ALL);
return this;
}
public ViewHolder setTypeface(Typeface typeface, int... viewIds) {
for (int viewId : viewIds) {
TextView view = getView(viewId);
view.setTypeface(typeface);
view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
return this;
}
public ViewHolder setProgress(int viewId, int progress) {
ProgressBar view = getView(viewId);
view.setProgress(progress);
return this;
}
public ViewHolder setProgress(int viewId, int progress, int max) {
ProgressBar view = getView(viewId);
view.setMax(max);
view.setProgress(progress);
return this;
}
public ViewHolder setMax(int viewId, int max) {
ProgressBar view = getView(viewId);
view.setMax(max);
return this;
}
public ViewHolder setRating(int viewId, float rating) {
RatingBar view = getView(viewId);
view.setRating(rating);
return this;
}
public ViewHolder setRating(int viewId, float rating, int max) {
RatingBar view = getView(viewId);
view.setMax(max);
view.setRating(rating);
return this;
}
public ViewHolder setTag(int viewId, Object tag) {
View view = getView(viewId);
view.setTag(tag);
return this;
}
public ViewHolder setTag(int viewId, int key, Object tag) {
View view = getView(viewId);
view.setTag(key, tag);
return this;
}
public ViewHolder setChecked(int viewId, boolean checked) {
Checkable view = (Checkable) getView(viewId);
view.setChecked(checked);
return this;
}
/**
* 关于事件的
*/
public ViewHolder setOnClickListener(int viewId,
View.OnClickListener listener) {
View view = getView(viewId);
view.setOnClickListener(listener);
return this;
}
public ViewHolder setOnTouchListener(int viewId,
View.OnTouchListener listener) {
View view = getView(viewId);
view.setOnTouchListener(listener);
return this;
}
public ViewHolder setOnLongClickListener(int viewId,
View.OnLongClickListener listener) {
View view = getView(viewId);
view.setOnLongClickListener(listener);
return this;
}
public void updatePosition(int position) {
mPosition = position;
}
public int getLayoutId() {
return mLayoutId;
}
/**
* 隐藏或展示Item
*
* @param visible
*/
public void setItemVisible(boolean visible) {
View v = getConvertView();
if (null != v) {
if (visible) {
if (null != v.getLayoutParams()) {
v.getLayoutParams().width = AbsListView.LayoutParams.MATCH_PARENT;
v.getLayoutParams().height = AbsListView.LayoutParams.WRAP_CONTENT;
} else {
v.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
}
v.setVisibility(View.VISIBLE);
} else {
if (null != v.getLayoutParams()) {
v.getLayoutParams().width = -1;
v.getLayoutParams().height = 1;
} else {
v.setLayoutParams(new AbsListView.LayoutParams(-1, 1));
}
v.setVisibility(View.GONE);
}
}
}
public void setHItemVisible(boolean visible) {
View v = getConvertView();
if (null != v) {
if (visible) {
if (null != v.getLayoutParams()) {
v.getLayoutParams().width = AbsListView.LayoutParams.WRAP_CONTENT;
v.getLayoutParams().height = AbsListView.LayoutParams.WRAP_CONTENT;
} else {
v.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
}
v.setVisibility(View.VISIBLE);
} else {
if (null != v.getLayoutParams()) {
v.getLayoutParams().width = -1;
v.getLayoutParams().height = 1;
} else {
v.setLayoutParams(new AbsListView.LayoutParams(-1, 1));
}
v.setVisibility(View.GONE);
}
}
}
}
使用
mRv = (RecyclerView) findViewById(R.id.rv);
mRv.setLayoutManager(mManager = new LinearLayoutManager(this));
mAdapter = new CityAdapter(this, mDatas);
mHeaderAdapter = new HeaderRecyclerAndFooterWrapperAdapter(mAdapter) {
@Override
protected void onBindHeaderHolder(ViewHolder holder, int headerPos, int layoutId, Object o) {
holder.setText(R.id.tvCity, (String) o);
}
};
mHeaderAdapter.setHeaderView(R.layout.item_city, "测试头部");
mRv.setAdapter(mHeaderAdapter);