效果图:
原理:将Header当成普通的item添加上去
onAttachtoRecyclerView方法:判断position位置的item是不是Header,如果是Header则返回gridManager.getSpanCount()(表示当前item占据spanCount个单元格),否则占据1个单元格。
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) manager);
gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return getItemViewType(position) == TYPE_HEADER
? gridManager.getSpanCount() : 1;
}
});
}
}
//position==0,返回Header
@Override
public int getItemViewType(int position) {
if (position == 0) return TYPE_HEADER;
else {
......
}
}
//根据viewType 确定返回Header或是普通item
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == TYPE_HEADER) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_header_homepage, parent, false);
return new HeaderViewHolder(view);
}
if (viewType == VIEW_TYPE_ONE) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_onepic_homepage, parent, false);
return new HomePageOnePicViewHolder(view);
} else {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_threepic_homepage, parent, false);
return new HomePageThreePicViewHolder(view);
}
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
if (holder.getItemViewType() == TYPE_HEADER) {
final HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
......
return;
}
final int pos = getRealPosition(holder);
final UserHomePageBean userHomePageItem = userHomePageBeanList.get(pos);
if (holder.getItemViewType() == VIEW_TYPE_THREE) {
HomePageThreePicViewHolder homePageThreePicViewHolder = (HomePageThreePicViewHolder) holder;
......
}
}
//因为item的总数量是根据beanList判断的,添加了Header但是并没有在beanList中增加(因为数据结构不一致),所以添加了Header后itemCount应该加1
@Override
public int getItemCount() {
return mHeaderView == false ? userHomePageBeanList.size() : userHomePageBeanList.size() + 1;
}
//得到真正的position,因为在onBindView里要根据position来获得对应位置的beanList的数据,添加了Header之后,元素个数增加了1个,所以用原来的position得到的bean并不是对应位置的bean,而是正确的bean的后一个。所以如果添加了Header,实际position应该是原来的减1。
public int getRealPosition(ViewHolder holder) {
int position = holder.getLayoutPosition();
return mHeaderView == false ? position : position - 1;
}