AnZ
AnZ

Reputation: 1060

Decorate RecyclerView using ItemDecoration after position

Is it possible to start decoration starting from some position?

In my case the decoration is horizontal spacing between elements in pixels:

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;
    }
}

Therefore, is it possible to NOT add this spacing after first row and start from second one?

Upvotes: 0

Views: 552

Answers (1)

shobhan
shobhan

Reputation: 1518

Simply exclude the 1st item from decoration like,

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;
        }
    }
}

Upvotes: 2

Related Questions