0

我的问题是我一直试图在 staggeredGrid 的元素之间放置一些黑线,但我似乎无法让它正常工作。我发现这个类在每个单独的项目之间添加了空格:

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private final int mSpace;
    public SpacesItemDecoration(int space) {
        this.mSpace = space;
    }
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.left = mSpace;
        outRect.right = mSpace;
        outRect.bottom = mSpace;
        // Add top margin only for the first item to avoid double space between items
        if (parent.getChildAdapterPosition(view) == 0)
            outRect.top = mSpace;
    }
}

我怎样才能调整它来为这些空间着色?

4

1 回答 1

0

您只需要覆盖onDraw()即可在视图上实际绘制某些内容。请注意,如果添加多个装饰,顺序很重要。

下面是一些在视图底部绘制边框的示例代码,您需要绘制所有 4 个边框。

public class DividerDecoration extends RecyclerView.ItemDecoration {

private final Paint mPaint;
private int mHeightDp;


public DividerDecoration(Context context, int color, float heightDp) {
    mPaint = new Paint();
    mPaint.setStyle(Paint.Style.FILL);
    mPaint.setColor(color);
    mHeightDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, heightDp, context.getResources().getDisplayMetrics());
}

@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    for (int i = 0; i < parent.getChildCount(); i++) {
        View view = parent.getChildAt(i);
            c.drawRect(view.getLeft(), view.getBottom(), view.getRight(), view.getBottom() + mHeightDp, mPaint);
    }
}

}

您也可以在此处查看有关绘制底部分隔线的完整示例。

于 2015-11-04T19:05:42.957 回答