GridLayoutManager分割线
时间: 2023-08-11 13:06:51 浏览: 86
要在 GridLayoutManager 中添加分割线,可以使用 RecyclerView.ItemDecoration 类来实现。以下是一个示例代码片段,可以在 GridLayoutManager 中添加分割线:
```java
public class GridDividerItemDecoration extends RecyclerView.ItemDecoration {
private int spacing;
public GridDividerItemDecoration(int spacing) {
this.spacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
int spanCount = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount();
int column = position % spanCount;
outRect.top = spacing;
outRect.bottom = spacing;
outRect.left = spacing;
outRect.right = spacing;
if (position < spanCount) {
outRect.top = 0;
}
if (column == 0) {
outRect.left = 0;
}
if ((column + 1) == spanCount) {
outRect.right = 0;
}
}
}
```
然后,在设置 RecyclerView 的 Adapter 之后,可以将分割线添加到 RecyclerView 上,如下所示:
```java
int spacing = getResources().getDimensionPixelSize(R.dimen.grid_spacing);
recyclerView.addItemDecoration(new GridDividerItemDecoration(spacing));
```
其中,R.dimen.grid_spacing 是一个在 dimens.xml 文件中定义的尺寸值,表示每个格子之间的间距。你可以根据实际情况进行调整。
阅读全文