请在Chrome、Firefox等现代浏览器浏览本站。如果有问题请 点击加我 QQ 说你的建议。

Android RecyclerView设置Item间距

安卓教程 sendtion 3824℃ 0评论

RecyclerView没有可以直接设置间距的属性,但是可以用ItemDecoration来实现。需要自定义ItemDecoration,继承自RecyclerView.ItemDecoration.

代码如下:

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
  private int space;

  public SpacesItemDecoration(int space) {
    this.space = space;
  }

  @Override
  public void getItemOffsets(Rect outRect, View view, 
      RecyclerView parent, RecyclerView.State state) {
    outRect.left = space;
    outRect.right = space;
    outRect.bottom = space;

    // Add top margin only for the first item to avoid double space between items
    if(parent.getChildPosition(view) == 0)
        outRect.top = space;
  }
}

然后,初始化RecyclerView之后,设置间距。代码如下:

recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
int itemSpacing = 8;
recyclerView.addItemDecoration(new SpacesItemDecoration(itemSpacing));

转载请注明:风的记忆 » Android RecyclerView设置Item间距

喜欢 (0)or分享 (0)