它比这简单得多,RecyclerView
已经有了这个功能:只需设置android:clipToPadding="false"
为RecyclerView
XML,这样填充就不会剪掉你的项目.
所以对于你的例子:
我通常使用ItemDecoration实现这种效果,而不是使用填充.
public class PaddingItemDecoration extends RecyclerView.ItemDecoration { private final int size; public PaddingItemDecoration(int size) { this.size = size; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); // Apply offset only to first item if (parent.getChildAdapterPosition(view) == 0) { outRect.left += size; } } }
然后当你设置你的RecyclerView
:
int size = ... // Get the offset that you want RecyclerView recyclerView = ... recyclerView.addItemDecoration(new PaddingItemDecoration(size));