AndroidRecyclerviewGridLayoutManager列间距 - Android Recyclerview GridLayoutManager column spacing

解决方案:
RecyclerViews支持ItemDecoration的概念:特殊补偿和绘画在每个元素。见这个答案,您可以使用然后通过添加
原文:

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));
网友:使用“outRect。顶级=空间outRect和删除。底,如果你不想惹“如果第一的位置”。;-)

(原文:Use 'outRect.top = space' and remove 'outRect.bottom' if you don't want to mess with the 'if for the first position'. ;-])

网友:@zatziky——是的,如果你已经在使用顶部和底部填充作为你的一部分(使用),然后你可以稍微重组的事情。然而,如果你不你只是移动如果检查最后一次(就像你仍然希望底部填充最后一项)。

(原文:@zatziky - yep, if you already use top and bottom padding as part of your RecyclerView (and useclipToPadding="false"), then you can restructure things slightly. If you don't however, you'd just be moving the if check to be the last time (as you'd still want the bottom padding on the last item).)

网友:我试着这个,除非我添加了Android:clipToPadding=“false”和android:填充=“@dimen/间距”RecyclerView外面的间距不符合项之间的间距。我已经试了所有下面的答案,认为@yqritc是最干净,最简单的解决方案。

(原文:I tried this and unless I added android:clipToPadding="false" and android:padding="@dimen/spacing" to the RecyclerView the outside spacing did not match the spacing between items. I have tried all the answers below and think the solution by @yqritc was the cleanest and simplest.)

网友:@ianhanniballake,而这是在使用单孔布局管理器,这对多跨布局管理器失败。

(原文:@ianhanniballake, while this works when using a single span layout manager, it fails for multi-span layout manager.)

网友:值得提及,你必须修改outRect的所有字段。否则你可以抵消之前的观点。

(原文:It worth to mention, that you have to modify all fields of outRect. otherwise you can get the offset of the previous view.)

解决方案:
代码运行良好,每一列有相同的宽度:使用它:1)没有边缘2)与边缘
原文:

Following code works well, and each column has same width:

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }
}

To use it:

1) no edge

enter image description here

int spanCount = 3;
int spacing = 50;
boolean includeEdge = false;
recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));

2) with edge

enter image description here

int spanCount = 3;
int spacing = 50;
boolean includeEdge = true;
recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
网友:谢谢,它太棒了!

(原文:thanks, It works great!)

网友:工作除非你有项目,有各种各样的跨越,像标题。

(原文:Works unless you have items that have various spans, like headers.)

网友:工作就像一个魅力!

(原文:Worked like a charm!)

网友:似乎只有在垂直模式工作

(原文:Seems to only work for vertical mode)

解决方案:
下面是一步一步简单的解决方案,如果你想要的物品和周围的相等的间距等于项目大小。ItemOffsetDecoration实现在你的源代码,添加ItemOffsetDecorationrecyclerview。项抵消值应该是您想要添加一半大小的实际价值之间的空间项目。同时,设置项目抵消值作为其recyclerview填充,并指定android:clipToPadding=false。完成了。
原文:

The following is the step-by-step simple solution if you want the equal spacing around items and equal item sizes.

ItemOffsetDecoration

public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {

    private int mItemOffset;

    public ItemOffsetDecoration(int itemOffset) {
        mItemOffset = itemOffset;
    }

    public ItemOffsetDecoration(@NonNull Context context, @DimenRes int itemOffsetId) {
        this(context.getResources().getDimensionPixelSize(itemOffsetId));
    }

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

Implementation

In your source code, add ItemOffsetDecoration to your recyclerview.
Item offset value should be half size of the actual value you want to add as space between items.

mRecyclerView.setLayoutManager(new GridLayoutManager(context, NUM_COLUMNS);
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context, R.dimen.item_offset);
mRecyclerView.addItemDecoration(itemDecoration);

Also, set item offset value as padding for its recyclerview, and specify android:clipToPadding=false.

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:padding="@dimen/item_offset"/>

DONE.

网友:简单而优雅

(原文:Simple and elegant)

网友:最佳答案——伟大的工作!

(原文:Best answer here - great job!)

网友:最佳答案-m8:感谢)

(原文:best answer- thanks m8 :))

网友:完美!就像一个魅力。

(原文:perfect! Works like a charm.)

网友:好先生!!

(原文:Well done sir!!)

解决方案:
试试这个。它会照顾相等的间距。作品都使用列表、网格,进行。编辑更新的代码应该处理的大部分角落案件与跨越,取向,等等。请注意,如果使用setSpanSizeLookupGridLayoutManager(),设置setSpanIndexCacheEnabled()建议由于性能的原因。与进行注意,似乎,似乎有一个错误的索引孩子变得古怪,很难跟踪,所以下面的代码与StaggeredGridLayoutManager可能不会工作得很好。希望它可以帮助。
原文:

Try this. It'll take care of equal spacing all around. Works both with List, Grid, and StaggeredGrid.

Edited

The updated code should handle most of the corner cases with spans, orientation, etc. Note that if using setSpanSizeLookup() with GridLayoutManager, setting setSpanIndexCacheEnabled() is recommended for performance reasons.

Note, it seems that with StaggeredGrid, there's seems to be a bug where the index of the children gets wacky and hard to track so the code below might not work very well with StaggeredGridLayoutManager.

public class ListSpacingDecoration extends RecyclerView.ItemDecoration {

  private static final int VERTICAL = OrientationHelper.VERTICAL;

  private int orientation = -1;
  private int spanCount = -1;
  private int spacing;
  private int halfSpacing;


  public ListSpacingDecoration(Context context, @DimenRes int spacingDimen) {

    spacing = context.getResources().getDimensionPixelSize(spacingDimen);
    halfSpacing = spacing / 2;
  }

  public ListSpacingDecoration(int spacingPx) {

    spacing = spacingPx;
    halfSpacing = spacing / 2;
  }

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

    super.getItemOffsets(outRect, view, parent, state);

    if (orientation == -1) {
        orientation = getOrientation(parent);
    }

    if (spanCount == -1) {
        spanCount = getTotalSpan(parent);
    }

    int childCount = parent.getLayoutManager().getItemCount();
    int childIndex = parent.getChildAdapterPosition(view);

    int itemSpanSize = getItemSpanSize(parent, childIndex);
    int spanIndex = getItemSpanIndex(parent, childIndex);

    /* INVALID SPAN */
    if (spanCount < 1) return;

    setSpacings(outRect, parent, childCount, childIndex, itemSpanSize, spanIndex);
  }

  protected void setSpacings(Rect outRect, RecyclerView parent, int childCount, int childIndex, int itemSpanSize, int spanIndex) {

    outRect.top = halfSpacing;
    outRect.bottom = halfSpacing;
    outRect.left = halfSpacing;
    outRect.right = halfSpacing;

    if (isTopEdge(parent, childCount, childIndex, itemSpanSize, spanIndex)) {
        outRect.top = spacing;
    }

    if (isLeftEdge(parent, childCount, childIndex, itemSpanSize, spanIndex)) {
        outRect.left = spacing;
    }

    if (isRightEdge(parent, childCount, childIndex, itemSpanSize, spanIndex)) {
        outRect.right = spacing;
    }

    if (isBottomEdge(parent, childCount, childIndex, itemSpanSize, spanIndex)) {
        outRect.bottom = spacing;
    }
  }

  @SuppressWarnings("all")
  protected int getTotalSpan(RecyclerView parent) {

    RecyclerView.LayoutManager mgr = parent.getLayoutManager();
    if (mgr instanceof GridLayoutManager) {
        return ((GridLayoutManager) mgr).getSpanCount();
    } else if (mgr instanceof StaggeredGridLayoutManager) {
        return ((StaggeredGridLayoutManager) mgr).getSpanCount();
    } else if (mgr instanceof LinearLayoutManager) {
        return 1;
    }

    return -1;
  }

  @SuppressWarnings("all")
  protected int getItemSpanSize(RecyclerView parent, int childIndex) {

    RecyclerView.LayoutManager mgr = parent.getLayoutManager();
    if (mgr instanceof GridLayoutManager) {
        return ((GridLayoutManager) mgr).getSpanSizeLookup().getSpanSize(childIndex);
    } else if (mgr instanceof StaggeredGridLayoutManager) {
        return 1;
    } else if (mgr instanceof LinearLayoutManager) {
        return 1;
    }

    return -1;
  }

  @SuppressWarnings("all")
  protected int getItemSpanIndex(RecyclerView parent, int childIndex) {

    RecyclerView.LayoutManager mgr = parent.getLayoutManager();
    if (mgr instanceof GridLayoutManager) {
        return ((GridLayoutManager) mgr).getSpanSizeLookup().getSpanIndex(childIndex, spanCount);
    } else if (mgr instanceof StaggeredGridLayoutManager) {
        return childIndex % spanCount;
    } else if (mgr instanceof LinearLayoutManager) {
        return 0;
    }

    return -1;
  }

  @SuppressWarnings("all")
  protected int getOrientation(RecyclerView parent) {

    RecyclerView.LayoutManager mgr = parent.getLayoutManager();
    if (mgr instanceof LinearLayoutManager) {
        return ((LinearLayoutManager) mgr).getOrientation();
    } else if (mgr instanceof GridLayoutManager) {
        return ((GridLayoutManager) mgr).getOrientation();
    } else if (mgr instanceof StaggeredGridLayoutManager) {
        return ((StaggeredGridLayoutManager) mgr).getOrientation();
    }

    return VERTICAL;
  }

  protected boolean isLeftEdge(RecyclerView parent, int childCount, int childIndex, int itemSpanSize, int spanIndex) {

    if (orientation == VERTICAL) {

        return spanIndex == 0;

    } else {

        return (childIndex == 0) || isFirstItemEdgeValid((childIndex < spanCount), parent, childIndex);
    }
  }

  protected boolean isRightEdge(RecyclerView parent, int childCount, int childIndex, int itemSpanSize, int spanIndex) {

    if (orientation == VERTICAL) {

        return (spanIndex + itemSpanSize) == spanCount;

    } else {

        return isLastItemEdgeValid((childIndex >= childCount - spanCount), parent, childCount, childIndex, spanIndex);
    }
  }

  protected boolean isTopEdge(RecyclerView parent, int childCount, int childIndex, int itemSpanSize, int spanIndex) {

    if (orientation == VERTICAL) {

        return (childIndex == 0) || isFirstItemEdgeValid((childIndex < spanCount), parent, childIndex);

    } else {

        return spanIndex == 0;
    }
  }

  protected boolean isBottomEdge(RecyclerView parent, int childCount, int childIndex, int itemSpanSize, int spanIndex) {

    if (orientation == VERTICAL) {

        return isLastItemEdgeValid((childIndex >= childCount - spanCount), parent, childCount, childIndex, spanIndex);

    } else {

        return (spanIndex + itemSpanSize) == spanCount;
    }
  }

  protected boolean isFirstItemEdgeValid(boolean isOneOfFirstItems, RecyclerView parent, int childIndex) {

    int totalSpanArea = 0;
    if (isOneOfFirstItems) {
        for (int i = childIndex; i >= 0; i--) {
            totalSpanArea = totalSpanArea + getItemSpanSize(parent, i);
        }
    }

    return isOneOfFirstItems && totalSpanArea <= spanCount;
  }

  protected boolean isLastItemEdgeValid(boolean isOneOfLastItems, RecyclerView parent, int childCount, int childIndex, int spanIndex) {

    int totalSpanRemaining = 0;
    if (isOneOfLastItems) {
        for (int i = childIndex; i < childCount; i++) {
            totalSpanRemaining = totalSpanRemaining + getItemSpanSize(parent, i);
        }
    }

    return isOneOfLastItems && (totalSpanRemaining <= spanCount - spanIndex);
  }
}

Hope it helps.

网友:非常感谢对这个答案

(原文:thnx for this answer)

网友:这应该是验证答案。谢谢你!

(原文:This should be the verified answer. Thank you.)

网友:我有双跨后的第一道物品。这是因为parent.getChildCount第一项()返回1,2第二等等。所以,我建议添加空间项目的前边缘:outRect。顶级=childIndex<spancount吗?spacinginpixels:0,和每个条目的添加底空间:outrect。底=spacinginpixels;

(原文:I've got double span just after first line of items. It happens because parent.getChildCount() returns 1 for first item, 2 for second and so on. So, I suggest add space to items of the top edge like: outRect.top = childIndex < spanCount ? spacingInPixels : 0; And add bottom space for each item: outRect.bottom = spacingInPixels;)

网友:在滚动的时候RecyclerView,间距变了。

(原文:At the time of scrolling RecyclerView, spacing changed.)

网友:我认为parent.getChildCount()应该改为“parent.getLayoutManager().getItemCount()”。同时,isBottomEdge功能需要改变“回归childIndex>=childCount-spanCount+spanIndex”。改变这些之后,我得到了相等的间距。但是请注意,这个解决方案不给我等于项目大小如果跨数大于2因为偏移值取决于位置是不同的。

(原文:I think parent.getChildCount() should be changed to "parent.getLayoutManager().getItemCount()". Also, isBottomEdge function need to be changed to "return childIndex >= childCount - spanCount + spanIndex". After changing these, I got equal spacing. But please note that this solution does not give me equal item sizes if span count is greater than 2 since offset value is different depending on position.)

解决方案:
下面的代码将处理StaggeredGridLayoutManager、GridLayoutManagerLinearLayoutManager。然后使用它
原文:

The following code will handle StaggeredGridLayoutManager, GridLayoutManager, and LinearLayoutManager.

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

    private int halfSpace;

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

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

        if (parent.getPaddingLeft() != halfSpace) {
            parent.setPadding(halfSpace, halfSpace, halfSpace, halfSpace);
            parent.setClipToPadding(false);
        }

        outRect.top = halfSpace;
        outRect.bottom = halfSpace;
        outRect.left = halfSpace;
        outRect.right = halfSpace;
    }
}

Then use it

mRecyclerView.addItemDecoration(new SpacesItemDecoration(mMargin));
网友:这是最简单的一个。一个重要的事情是你也要添加填充到父在xml。在我的例子中,它的工作方式。谢谢。

(原文:This is the most simple one. One important thing is you also got to add the padding to the parent in the xml. In my case, it work that way. Thanks.)

网友:实际上增加了填充到父(回收商的观点)。

(原文:The SpaceItemDecoration actually adds the padding to the parent (the recycler view).)

网友:只填充出现(右侧)当我没有设置填充到父在xml中

(原文:only halfSpace padding appeared(to the right side) when I had not set the padding to the parent in xml)

网友:只是缺失的右边?也许你有半空间设置为leftPadding左边已经在xml,这段代码只剩下检查填充设置RecyclerView与否。

(原文:It was only missing on the right side? It may be that you have half space set as the leftPadding on the left side already in the xml and this code only checks if the left padding is set on the RecyclerView or not.)

网友:这是最简洁的解决方案!

(原文:this is the most concise solution!)

解决方案:
回答上面有澄清方法设置边缘处理GridLayoutManager和LinearLayoutManager。但是StaggeredGridLayoutManagerPirdadSakhizada的回答说,“与StaggeredGridLayoutManager可能不会工作得很好。“这应该对indexOfSpan问题。你可以通过这种方式:
原文:

Answers above have clarified ways to set margin handling GridLayoutManager and LinearLayoutManager.

But for StaggeredGridLayoutManager, Pirdad Sakhizada's answer say it "might not work very well with StaggeredGridLayoutManager." It should be the problem about indexOfSpan.

You can get it by this way:

private static class MyItemDecoration extends RecyclerView.ItemDecoration {
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int index = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在现有省、市港口信息化系统进行有效整合基础上,借鉴新 一代的感知-传输-应用技术体系,实现对码头、船舶、货物、重 大危险源、危险货物装卸过程、航管航运等管理要素的全面感知、 有效传输和按需定制服务,为行政管理人员和相关单位及人员提 供高效的管理辅助,并为公众提供便捷、实时的水运信息服务。 建立信息整合、交换和共享机制,建立健全信息化管理支撑 体系,以及相关标准规范和安全保障体系;按照“绿色循环低碳” 交通的要求,搭建高效、弹性、高可扩展性的基于虚拟技术的信 息基础设施,支撑信息平台低成本运行,实现电子政务建设和服务模式的转变。 实现以感知港口、感知船舶、感知货物为手段,以港航智能 分析、科学决策、高效服务为目的和核心理念,构建“智慧港口”的发展体系。 结合“智慧港口”相关业务工作特点及信息化现状的实际情况,本项目具体建设目标为: 一张图(即GIS 地理信息服务平台) 在建设岸线、港口、港区、码头、泊位等港口主要基础资源图层上,建设GIS 地理信息服务平台,在此基础上依次接入和叠加规划建设、经营、安全、航管等相关业务应用专题数据,并叠 加动态数据,如 AIS/GPS/移动平台数据,逐步建成航运管理处 "一张图"。系统支持扩展框架,方便未来更多应用资源的逐步整合。 现场执法监管系统 基于港口(航管)执法基地建设规划,依托统一的执法区域 管理和数字化监控平台,通过加强对辖区内的监控,结合移动平 台,形成完整的多维路径和信息追踪,真正做到问题能发现、事态能控制、突发问题能解决。 运行监测和辅助决策系统 对区域港口与航运业务日常所需填报及监测的数据经过科 学归纳及分析,采用统一平台,消除重复的填报数据,进行企业 输入和自动录入,并进行系统智能判断,避免填入错误的数据, 输入的数据经过智能组合,自动生成各业务部门所需的数据报 表,包括字段、格式,都可以根据需要进行定制,同时满足扩展 性需要,当有新的业务监测数据表需要产生时,系统将分析新的 需求,将所需字段融合进入日常监测和决策辅助平台的统一平台中,并生成新的所需业务数据监测及决策表。 综合指挥调度系统 建设以港航应急指挥中心为枢纽,以各级管理部门和经营港 口企业为节点,快速调度、信息共享的通信网络,满足应急处置中所需要的信息采集、指挥调度和过程监控等通信保障任务。 设计思路 根据项目的建设目标和“智慧港口”信息化平台的总体框架、 设计思路、建设内容及保障措施,围绕业务协同、信息共享,充 分考虑各航运(港政)管理处内部管理的需求,平台采用“全面 整合、重点补充、突出共享、逐步完善”策略,加强重点区域或 运输通道交通基础设施、运载装备、运行环境的监测监控,完善 运行协调、应急处置通信手段,促进跨区域、跨部门信息共享和业务协同。 以“统筹协调、综合监管”为目标,以提供综合、动态、实 时、准确、实用的安全畅通和应急数据共享为核心,围绕“保畅通、抓安全、促应急"等实际需求来建设智慧港口信息化平台。 系统充分整合和利用航运管理处现有相关信息资源,以地理 信息技术、网络视频技术、互联网技术、移动通信技术、云计算 技术为支撑,结合航运管理处专网与行业数据交换平台,构建航 运管理处与各部门之间智慧、畅通、安全、高效、绿色低碳的智 慧港口信息化平台。 系统充分考虑航运管理处安全法规及安全职责今后的变化 与发展趋势,应用目前主流的、成熟的应用技术,内联外引,优势互补,使系统建设具备良好的开放性、扩展性、可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值