在位置后使用ItemDecoration装饰RecyclerView

时间:2016-04-05 13:07:45

标签: android android-recyclerview

是否可以从某个位置开始装饰?

在我的例子中,装饰是元素之间的水平间距(以像素为单位):

public class HorizontalSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int mHorizontalSpaceHeight;

    public HorizontalSpaceItemDecoration(int mHorizontalSpaceHeight) {
        this.mHorizontalSpaceHeight = mHorizontalSpaceHeight;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                           RecyclerView.State state) {
        outRect.bottom = mHorizontalSpaceHeight;
    }
}

因此,是否可以在第一行之后添加此间距并从第二行开始?

1 个答案:

答案 0 :(得分:2)

只需从装饰中排除第一项,

public class HorizontalSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int mHorizontalSpaceHeight;

    public HorizontalSpaceItemDecoration(int mHorizontalSpaceHeight) {
        this.mHorizontalSpaceHeight = mHorizontalSpaceHeight;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                           RecyclerView.State state) {
        int itemPosition = parent.getChildPosition(view);
        if(itemPosition>0){ //here we are excluding 1st item 
           outRect.bottom = mHorizontalSpaceHeight;
        }
    }
}