laaptu
laaptu

Reputation: 2973

Android RecyclerView finding out first and last view on ItemDecoration

Here is my scenario

Upvotes: 25

Views: 22185

Answers (1)

Ryan Amaral
Ryan Amaral

Reputation: 4289

Is there any other way to access RecyclerView first and last child on ItemDecoration so that later on removing and adding items won't have any problem.

Yes. You can achieve what you want only by implementing your own ItemDecoration.

To get the current item/child position:

int position = parent.getChildAdapterPosition(view);

To get the number of items/childs:

int itemCount = state.getItemCount();

With this you can add a space on the first and last child of your RecyclerView.


Now changing your code for this approach you get:

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);

    //your padding...

    final int itemPosition = parent.getChildAdapterPosition(view);
    if (itemPosition == RecyclerView.NO_POSITION) {
        return;
    }

    final int itemCount = state.getItemCount();

    /** first position */
    if (itemPosition == 0) {
        outRect.set(padding, padding, 0, padding);
    }
    /** last position */
    else if (itemCount > 0 && itemPosition == itemCount - 1) {
        outRect.set(0, padding, padding, padding);
    }
    /** positions between first and last */
    else {
        outRect.set(0, padding, 0, padding);
    }
}

Bonus: If you are looking to give padding to all items of the RecyclerView take a look at the Gist I've created: https://gist.github.com/ryanamaral/93b5bd95412baf85a81a

Upvotes: 70

Related Questions