android gridlayoutmanager 分割线
时间: 2023-08-11 17:06:55 浏览: 161
要在 Android 中使用 GridLayoutManager 显示分割线,你可以使用 RecyclerView.ItemDecoration 类来实现。下面是一个例子:
1. 创建一个分割线类:
```java
public class GridDividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public GridDividerItemDecoration(Context context) {
mDivider = ContextCompat.getDrawable(context, R.drawable.grid_divider);
}
@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
int dividerWidth = mDivider.getIntrinsicWidth();
int dividerHeight = mDivider.getIntrinsicHeight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + dividerHeight;
int left = child.getRight() + params.rightMargin;
int right = left + dividerWidth;
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(canvas);
}
}
}
```
2. 在你的 RecyclerView 中添加分割线:
```java
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
GridDividerItemDecoration dividerItemDecoration = new GridDividerItemDecoration(this);
recyclerView.addItemDecoration(dividerItemDecoration);
```
这个例子中,我们创建了一个 GridDividerItemDecoration 类来绘制分割线,然后将其添加到 RecyclerView 中。在这个例子中,我们使用 drawable/grid_divider.xml 文件来定义分割线的样式。你可以根据自己的需求修改这个文件。
阅读全文