Android RecyclerView 实现网格布局不满一排居中显示
要实现网格布局,不满一排居中,可以通过自定义 RecyclerView 的 LayoutManager 来实现。
首先,你需要自定义一个 GridLayoutManager,并重写 onLayoutChildren() 方法。在这个方法中,你可以获取到 RecyclerView 的宽度,然后计算每个子项的宽度。如果子项的总宽度小于 RecyclerView 的宽度,你可以将它们居中显示。
下面是一个简单的示例代码:
public class CenterGridLayoutManager extends GridLayoutManager {
public CenterGridLayoutManager(Context context, int spanCount) {
super(context, spanCount);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
super.onLayoutChildren(recycler, state);
int width = getWidth();
int totalWidth = 0;
for (int i = 0; i < getItemCount(); i++) {
View child = recycler.getViewForPosition(i);
addView(child);
measureChildWithMargins(child, 0, 0);
int childWidth = getDecoratedMeasuredWidth(child);
totalWidth += childWidth;
}
if (totalWidth < width) {
int offset = (width - totalWidth) / 2;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
int left = getDecoratedLeft(child) + offset;
int right = getDecoratedRight(child) + offset;
layoutDecorated(child, left, getDecoratedTop(child), right, getDecoratedBottom(child));
}
}
}
}
然后,在你的 Activity 或 Fragment 中,将这个自定义的 CenterGridLayoutManager 设置给 RecyclerView 即可:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
CenterGridLayoutManager layoutManager = new CenterGridLayoutManager(this, 3);
recyclerView.setLayoutManager(layoutManager);
注意,这个示例代码是假设你的网格布局是每行三列的,你可以根据实际情况修改 spanCount 的值。同时,你可能还需要调整子项的间距等布局属性来适应你的需求。
原文地址: https://www.cveoy.top/t/topic/qx7D 著作权归作者所有。请勿转载和采集!