StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
//设置SpanSizeLookup
layoutManager.setSpanSizeLookup(new StaggeredGridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
//返回跨度为1,即占据一行或一列的单元格数量
return 1;
}
});
//设置getItemOffsets
RecyclerView.ItemDecoration spacingDecoration = new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
//设置单元格之间的间距
outRect.set(10, 10, 10, 10);
}
};
mRecyclerView.addItemDecoration(spacingDecoration);
其中,SpanSizeLookup可以让每个单元格占据1列或1行,getItemOffsets可以设置单元格之间的间距。