gridlayoutmanager水平居中
时间: 2023-08-28 21:04:44 浏览: 132
要让 `GridLayoutManager` 水平居中,可以使用自定义的 `CenterGridLayoutManager` 类,如下所示:
```java
public class CenterGridLayoutManager extends GridLayoutManager {
public CenterGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public CenterGridLayoutManager(Context context, int spanCount) {
super(context, spanCount);
}
public CenterGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {
super(context, spanCount, orientation, reverseLayout);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
super.onLayoutChildren(recycler, state);
if (getItemCount() == 0) {
return;
}
int viewWidth = getWidth();
int viewHeight = getHeight();
int childWidth = getDecoratedMeasuredWidth(getChildAt(0));
int childHeight = getDecoratedMeasuredHeight(getChildAt(0));
int spanCount = getSpanCount();
int rowCount = getItemCount() / spanCount + (getItemCount() % spanCount == 0 ? 0 : 1);
int horizontalSpace = getDecoratedWidth(getChildAt(0)) * (spanCount - 1);
int verticalSpace = getDecoratedHeight(getChildAt(0)) * (rowCount - 1);
int totalWidth = childWidth * spanCount + horizontalSpace;
int totalHeight = childHeight * rowCount + verticalSpace;
int left = (viewWidth - totalWidth) / 2;
int top = (viewHeight - totalHeight) / 2;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
int position = getPosition(child);
int row = position / spanCount;
int col = position % spanCount;
int leftPos = left + col * childWidth;
int topPos = top + row * childHeight;
layoutDecorated(child, leftPos, topPos, leftPos + childWidth, topPos + childHeight);
}
}
}
```
该类继承了 `GridLayoutManager`,并在 `onLayoutChildren` 方法中实现了居中布局的逻辑。在 `onLayoutChildren` 方法中,先计算出所有子项的总宽度和总高度,然后计算出左边和上边的偏移量,最后遍历所有子项,分别设置子项的位置。设置子项位置时,根据子项所在的行列计算出左上角和右下角的坐标,然后调用 `layoutDecorated` 方法设置子项的位置。
阅读全文