Android Recyclerview GridLayoutManager列间距 [英] Android Recyclerview GridLayoutManager column spacing

查看:150
本文介绍了Android Recyclerview GridLayoutManager列间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用GridLayoutManager设置RecyclerView的列间距?
在布局中设置边距/填充没有效果。

解决方案

RecyclerViews支持 ItemDecoration :每个元素周围的特殊偏移和绘图。如此答案所示,您可以使用

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

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

@覆盖
公共无效getItemOffsets(矩形outRect,浏览视图,
RecyclerView父,RecyclerView.State状态){
outRect.left =空间;
outRect.right =空格;
outRect.bottom = space;

//仅为第一项添加顶部边距以避免项目之间的双倍空间
if(parent.getChildLayoutPosition(view)== 0){
outRect.top = space ;
} else {
outRect.top = 0;



code
$ b

然后通过 p>

  mRecyclerView =(RecyclerView)rootView.findViewById(R.id.my_recycler_view); 
int spacingInPixels = getResources()。getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));


How do you set the column spacing with a RecyclerView using a GridLayoutManager? Setting the margin/padding inside my layout has no effect.

解决方案

RecyclerViews support the concept of ItemDecoration: special offsets and drawing around each element. As seen in this answer, you can use

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.getChildLayoutPosition(view) == 0) {
        outRect.top = space;
    } else {
        outRect.top = 0;
    }
  }
}

Then add it via

mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));

这篇关于Android Recyclerview GridLayoutManager列间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆