我使用以下分隔线进行垂直线性布局,它工作得非常好:
public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {
private final int mVerticalSpaceHeight;
public VerticalSpaceItemDecoration(int mVerticalSpaceHeight) {
this.mVerticalSpaceHeight = mVerticalSpaceHeight;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1)
outRect.bottom = mVerticalSpaceHeight;
}
}
基于此,我尝试为 a 编写相同的装饰器GridLayout
,但问题是它正在切断我的项目。如下所示:
public class GridSpaceItemDecoration extends RecyclerView.ItemDecoration {
private final int mSpaceSize;
private final int mCols;
public GridSpaceItemDecoration(int spaceSize, int cols) {
this.mSpaceSize = spaceSize;
mCols = cols;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int rows = (int)Math.floor(parent.getAdapter().getItemCount() / mCols) + 1;
int pos = parent.getChildAdapterPosition(view);
int col = pos % mCols;
int row = (int)Math.floor(pos / mCols);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
if (col < mCols - 1)
outRect.right = /*params.rightMargin + view.getPaddingRight() +*/ mSpaceSize;
if (row < rows - 1)
outRect.bottom = /*params.leftMargin + view.getPaddingLeft() +*/ mSpaceSize;
}
}
两者的结果Decorators
如下(添加了调试颜色):
图像显示,在GridLayout
项目中被切断(在项目下方的文本中很容易看到)。我应该提一下,两者的适配器是相同的,我只是使用另一个LayoutManager
. 这些物品是固定尺寸的,这是我需要的!