RecyclerView 设置item之间的间距

项目需求给recyclerview添加item的间距,需要新增一个辅助类SpacesItemDecoration 。

代码如下:

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;
        outRect.bottom = space;

        // Add top margin only for the first item to avoid double space between items
        if (parent.getChildLayoutPosition(view) == 0)
            outRect.top = space;
    }

    public static int px2dp(float dpValue) {
        return (int) (0.5f + dpValue * Resources.getSystem().getDisplayMetrics().density);
    }

}

代码中设置item间距如下:

int space = 8;
        Recyclerview.addItemDecoration(new SpacesItemDecoration(SpacesItemDecoration.px2dp(space)));

还可以在item的布局里设置padding的值,这个值就是item之间的间距。

你可能感兴趣的:(踩坑记录,recyclerview,item间距,android)