给RecyclerView添加头部


一般通过  item类型  判断是否  头部view, 从而占据一行显示:

(recycleView内部实现了复用view,是通过getViewType得到类型判断是否复用还是调用adapter内方法创建新的view,so不建议返回position,每次都返回不同值会丧失复用机制。)

RecyclerView有3个布局管理器:

1;LinearLayoutManager

直接设置给RecyclerView,adapter中第一个item就是头部View

mRecyclerView.setLayoutManager(newandroid.support.v7.widget.LinearLayoutManager(this,

android.support.v7.widget.LinearLayoutManager.VERTICAL,//纵向布局

false));//从第一个item开始显示

2:GridLayoutManager

android.support.v7.widget.GridLayoutManager gridLayoutManager =newandroid.support.v7.widget.GridLayoutManager(this,3,android.support.v7.widget.GridLayoutManager.VERTICAL,false);

gridLayoutManager需要设置 setSpanSizeLookup,根据返回值决定该item占据几列,当前gridLayoutManager的列数是3,当返回3时就占据了一行显示。

gridLayoutManager.setSpanSizeLookup(newandroid.support.v7.widget.GridLayoutManager.SpanSizeLookup() {

@Override

public intgetSpanSize(intposition) {

returnposition ==0?3:1;

}

});

mRecyclerView.setLayoutManager(gridLayoutManager);

3;StaggeredGridLayoutManager

android.support.v7.widget.StaggeredGridLayoutManager staggeredGridLayoutManager =newandroid.support.v7.widget.StaggeredGridLayoutManager(3,android.support.v7.widget.StaggeredGridLayoutManager.VERTICAL);

mRecyclerView.setLayoutManager(staggeredGridLayoutManager);

设置了staggeredGridLayoutManager后需要在其adapter重写一个方法onViewAttachedToWindow

@Override

public voidonViewAttachedToWindow(android.support.v7.widget.RecyclerView.ViewHolder holder) {

super.onViewAttachedToWindow(holder);

android.view.ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();

if( lp  != null &&  lp  instanceof  android.support.v7.widget.StaggeredGridLayoutManager.LayoutParams) {

android.support.v7.widget.StaggeredGridLayoutManager.LayoutParams p = (android.support.v7.widget.StaggeredGridLayoutManager.LayoutParams) lp;

          /*主要代码 是 setFullSpan ,为true占据一行。网上有些帖子也是用这个方法,但是是重写StaggeredGridLayoutManager,在其onMeasure使用setFullSpan,有的在adapter的onBindViewHolder使用setFullSpan,但是我运行测试过有bug:不止第一个item占据一行,有时第一个item宽度很小,但是占据一行的情况。*/

          p.setFullSpan(holder.getLayoutPosition() ==0?true:false);

}

}

你可能感兴趣的:(给RecyclerView添加头部)