【问题标题】:GridLayoutManager set column and row countGridLayoutManager 设置列数和行数
【发布时间】:2016-11-25 17:22:35
【问题描述】:

我将GridLayoutManager 用于RecyclerViewGridLayoutManager.HORIZONTAL 方向。 SpanCount 对我来说不能正常工作,因为它取决于布局方向,但我知道我需要多少列和行。我该怎么办?

从文档到setSpanCount(int spanCount)

/**
 * Sets the number of spans to be laid out.
 * <p>
 * If {@link #getOrientation()} is {@link #VERTICAL}, this is the number of columns.
 * If {@link #getOrientation()} is {@link #HORIZONTAL}, this is the number of rows.
 *
 * @param spanCount The total number of spans in the grid
 * @see #getSpanCount()
 */

示例:我的RecyclerView 尺寸是match_parent,如果我有 9 个项目,我有 3x3 网格,如果我有 5 个项目,我有 3x2 网格,但我想要 2x3。

附:我不想设置GridLayoutManager.VERTICAL 布局方向。

屏幕截图不正确,我想要 2x3 网格。

【问题讨论】:

    标签: android android-recyclerview gridlayoutmanager


    【解决方案1】:

    您应该根据数据大小动态设置跨度计数。

    gridLayoutManager.setSpanCount( (int) Math.ceil( data.size() / 3f ) );
    

    因此,对于 7、8 和 9 个项目,您有 3 行。对于 4、5 和 6、2 行,依此类推。 使用 float (3f) 很重要,这样您的除法就不会被截断。

    【讨论】:

    • 当它说 4-6 个项目时,它会在行之间留出空间
    • 我也想做同样的事情,但是3f 必须是动态的,我怎样才能得到这个?我一无所知。
    【解决方案2】:

    在使用以下功能解决类似问题时创建了自定义 GridlayoutManager。

    为 RecyclerView 的子级创建一个默认的 LayoutParams 对象。

    它由generateDefaultLayoutParams 和另外3 个函数组成,用于为布局管理器设置特定(固定)布局参数。这允许为行和列设置特定的计数。

    相同的链接:- https://gist.github.com/KaveriKR/04bfef5ffc9c00a8b6fca503da497322

    编码愉快!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      相关资源
      最近更新 更多