我的问题是我一直试图在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;
}
}
我如何调整它来为这些空间着色?
答案 0 :(得分: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);
}
}
}
另外,您可以在绘制底部分隔符时查看完整示例here。