android gridlayout 分割线
时间: 2023-06-30 17:17:33 浏览: 194
要为 Android GridLayout 添加分割线,可以通过创建自定义的 GridItemDecoration 类来实现。这个类需要继承自 RecyclerView.ItemDecoration,然后重写其中的 onDraw() 和 getItemOffsets() 方法。
下面是一个示例代码,可以为 GridLayout 添加水平和垂直方向的分割线:
```java
public class GridItemDecoration extends RecyclerView.ItemDecoration {
private int horizontalSpacing;
private int verticalSpacing;
private Paint dividerPaint;
public GridItemDecoration(int horizontalSpacing, int verticalSpacing, int dividerColor) {
this.horizontalSpacing = horizontalSpacing;
this.verticalSpacing = verticalSpacing;
dividerPaint = new Paint();
dividerPaint.setColor(dividerColor);
dividerPaint.setStyle(Paint.Style.FILL);
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int childCount = parent.getChildCount();
int rowCount = parent.getAdapter().getItemCount() / parent.getChildCount();
int lastRowChildCount = parent.getAdapter().getItemCount() % parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
int childAdapterPosition = parent.getChildAdapterPosition(child);
int row = childAdapterPosition / rowCount;
int column = childAdapterPosition % rowCount;
if (row != 0) { // 绘制垂直方向的分割线
int left = child.getLeft() - horizontalSpacing / 2;
int right = child.getRight() + horizontalSpacing / 2;
int top = child.getTop() - verticalSpacing;
int bottom = child.getTop();
c.drawRect(left, top, right, bottom, dividerPaint);
}
if (column != 0) { // 绘制水平方向的分割线
int left = child.getLeft() - horizontalSpacing;
int right = child.getLeft();
int top = child.getTop() - verticalSpacing / 2;
int bottom = child.getBottom() + verticalSpacing / 2;
c.drawRect(left, top, right, bottom, dividerPaint);
}
// 绘制右边和底部的边框
if (column == rowCount - 1 && lastRowChildCount == 0) {
int left = child.getRight() - horizontalSpacing / 2;
int right = child.getRight() + horizontalSpacing / 2;
int top = child.getTop() - verticalSpacing;
int bottom = child.getBottom() + verticalSpacing;
c.drawRect(left, top, right, bottom, dividerPaint);
}
if (row == parent.getAdapter().getItemCount() / rowCount - 1) {
int left = child.getLeft() - horizontalSpacing;
int right = child.getRight() + horizontalSpacing;
int top = child.getBottom() - verticalSpacing / 2;
int bottom = child.getBottom() + verticalSpacing / 2;
c.drawRect(left, top, right, bottom, dividerPaint);
}
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.set(horizontalSpacing, verticalSpacing, horizontalSpacing, verticalSpacing);
}
}
```
使用方式:
```java
GridLayout gridLayout = findViewById(R.id.grid_layout);
gridLayout.addItemDecoration(new GridItemDecoration(16, 16, Color.GRAY));
```
其中,16 表示水平和垂直方向的间距,Color.GRAY 表示分割线的颜色。
阅读全文