检查你的 item 布局的最外层是否是
android:layout_width="match_parent"
附加均匀分布的方法
// 创建布局管理
GridLayoutManager manager = new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL,false);
rv_organ.addItemDecoration(new SpaceItemDecoration(0,2));
rv_organ.setLayoutManager(manager);
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
private int leftRight;
private int topBottom;
// leftRight 为横向间的距离 topBottom为纵向间距离
public SpaceItemDecoration(int leftRight, int topBottom) {
this.leftRight = leftRight;
this.topBottom = topBottom;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
// 竖直方向的
if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
// 最后一项需要 bottom
if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
outRect.bottom = topBottom;
}
outRect.top = topBottom;
outRect.left = leftRight;
outRect.right = leftRight;
} else {
// 最后一项需要 right
if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
outRect.right = leftRight;
}
outRect.top = topBottom;
outRect.left = leftRight;
outRect.bottom = topBottom;
}
}
}