赞
踩
重写adpater中的onAttachedToRecyclerView()方法:
动态改变布局管理器调整item行数: @Override //动态设置布局管理器行数 public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); if (manager instanceof GridLayoutManager && "score".equals(type)) { final GridLayoutManager gridManager = ((GridLayoutManager) manager); gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if (getItemViewType(position) == TYPE_HEADER) { return 2; //返回2展示一行 } else { return 1;//返回1展示两行 } } }); } }
重写adpater中的onViewAttachedToWindow()方法:
// 解决StaggeredGridLayoutManager占满一行
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
super.onViewAttachedToWindow(holder);
int type = holder.getItemViewType();
if (type == TYPE_HEADER) { //如果类型为头部就占满一行
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp instanceof StaggeredGridLayoutManager.LayoutParams) {
StaggeredGridLayoutManager.LayoutParams p =
(StaggeredGridLayoutManager.LayoutParams) lp;
p.setFullSpan(true);
}
}
}
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//防止第一行到顶部有空白区域
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
layoutManager.invalidateSpanAssignments();
}
});
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。