如果你的 RecyclerView 行之间存在间隙,有两种可能的原因:
针对第一种情况,你可以手动设置 item view 之间的间距。请参考以下代码:
public class SpaceItemDecoration extends RecyclerView.ItemDecoration { private int space;
public SpaceItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top = space;
} else {
outRect.top = 0;
}
}
}
注意:在上面的代码中,我们使用了 @{new com.example.myapp.SpaceItemDecoration(@dimen/activity_vertical_margin)} 来初始化 SpaceItemDecoration,其中 @dimen/activity_vertical_margin 是在 res/values/dimens.xml 文件中定义