tufekoi
tufekoi

Reputation: 991

Add item decoration to recycler view from the end of the adapter

I'm using a DividerItemDecoration on a GridLayout. It works fine for both direction, but it adds the divider at the bottom of the last row items, and I don't want that. I see that RecyclerView.addItemDecoration has this parameter :

@param index Position in the decoration chain to insert this decoration at. If this value is negative the decoration will be added at the end.

So I try to pass -3 thinking the decorations would be added from bottom to top skipping the 2 last items of the adapter. But it didn't.

I can I achieve this without creating a duplicate of DividerItemDecoration to simply change the loop iteration in drawVertical ?

Upvotes: 0

Views: 255

Answers (1)

Ferran
Ferran

Reputation: 1448

Create a new class

private class NoBottomDividerItemDecoration extends DividerItemDecoration {

    public NoBottomDividerItemDecoration(Context context, int orientation) {
        super(context, orientation);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1) {
            outRect.set(0, 0, 0, 0);
        }        
    }
}

Use this class instead of DividerItemDecoration. This will remove the last divider.

Upvotes: 1

Related Questions