Android RecyclerView 找出 ItemDecoration 上的第一个和最后一个视图

Android RecyclerView finding out first and last view on ItemDecoration

这是我的场景

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.

是的。您只能通过实现自己的 ItemDecoration.

来实现您想要的

获取当前item/child位置:

int position = parent.getChildAdapterPosition(view);

获取items/childs的人数:

int itemCount = state.getItemCount();

有了这个,您可以在 RecyclerView 的第一个和最后一个 child 上添加一个 space


现在为这种方法更改您的代码,您将获得:

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

奖励: 如果您希望为 RecyclerView 的所有项目提供填充,请查看我创建的 Gist : https://gist.github.com/ryanamaral/93b5bd95412baf85a81a