可以使用FlexboxLayoutManager和FlexboxItemDecoration来实现固定列数的布局。
在XML布局中定义使用FlexboxLayout,并设置布局属性:
然后在代码中,使用FlexboxLayoutManager设置固定列数:
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(context);
layoutManager.setFlexDirection(FlexDirection.ROW);
layoutManager.setFlexWrap(FlexWrap.WRAP);
layoutManager.setAlignItems(AlignItems.STRETCH);
layoutManager.setJustifyContent(JustifyContent.SPACE_BETWEEN);
layoutManager.setFlexItemCount(numColumns); //设置列数
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(layoutManager);
使用FlexboxItemDecoration设置间隔:
FlexboxItemDecoration itemDecoration = new FlexboxItemDecoration(context);
itemDecoration.setFlexDirection(FlexDirection.ROW);
itemDecoration.setJustifyContent(JustifyContent.SPACE_BETWEEN);
itemDecoration.setWithOffset(true);
itemDecoration.setHorizontalOffset(10); //设置水平方向间隔
itemDecoration.setVerticalOffset(10); //设置垂直方向间隔
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.addItemDecoration(itemDecoration);