RecyclerView实现多种item布局
1:动态改变每一行的列数(动态控制布局管理器):
重写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展示两行
}
}
});
}
}
注意:这个getSpanSize()方法返回值并不是要显示的列数。解释:getSpanSize返回值不是表示控制每行有几列,而是当前这个Item占这一行得几列( 参考文章
2:解决StaggeredGridLayoutManager占满一行:
重写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);
}
}
}
3.防止第一行到顶部有空白区域
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();
}
});