今天在用RecyclerView做一个横向视图的时间轴控件时发现item之间总有一些空隙,而且明明子item之间的padding为0,在上网找到可以通过addItemDecoration来改变item之间的间隔
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
//解决Item之间总是有空隙的问题,根据需要设置左右间隔为负数解决问题
//outRect.bottom = space;
// Add top margin only for the first item to avoid double space between items
//if (parent.getChildPosition(view) == 0)
//outRect.top = space;
}
}
先重写RecyclerView.ItemDecoration方法设置Item边距
mRecyclerView.addItemDecoration(new SpacesItemDecoration(-3));
最后为RecyclerView加一个addItemDecoration为-3解决间隙的问题
网友评论