【问题标题】:RecyclerView LayoutManager different span counts on different rowsRecyclerView LayoutManager 不同行上的不同跨度计数
【发布时间】:2015-06-29 09:33:26
【问题描述】:

我想要一个RecyclerView.LayoutManager,它允许我为不同的行指定不同的跨度计数作为重复模式。例如 2,3 有 10 个项目如下所示:

  -------------
  |     |     |
  |     |     |
  -------------
  |   |   |   |
  |   |   |   |
  -------------
  |     |     |
  |     |     |
  -------------
  |   |   |   |
  |   |   |   |
  -------------

我可以想办法用GridLayoutManagerSpanSizeLookup 破解这个问题,但是有没有人想出一个更简洁的方法来做到这一点?

【问题讨论】:

标签: android android-recyclerview


【解决方案1】:

要做你想做的事,你可能必须自己写LayoutManager

我认为这更容易:

    // Create a grid layout with 6 columns
    // (least common multiple of 2 and 3)
    GridLayoutManager layoutManager = new GridLayoutManager(this, 6);

    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            // 5 is the sum of items in one repeated section
            switch (position % 5) {
            // first two items span 3 columns each
            case 0:
            case 1:
                return 3;
            // next 3 items span 2 columns each
            case 2:
            case 3:
            case 4:
                return 2;
            }
            throw new IllegalStateException("internal error");
        }
    });

如果您的网格项目需要知道其跨度大小,您可以在ViewHolder 中找到它:

        // this line can return null when the view hasn't been added to the RecyclerView yet
        RecyclerView recyclerView = (RecyclerView) itemView.getParent();
        GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
        int spanSize = gridLayoutManager.getSpanSizeLookup().getSpanSize(getLayoutPosition());

【讨论】:

  • 你救了我的命
  • 效果很好,我们可以在运行时检查 onBindView 方法中的跨度计数吗?我想显示隐藏一些基于此的视图。
  • 我现在不明白为什么在某些项目上更改 spanSize 时,位置会更改。例如,第 4 项出现在更改的跨度项之前(第三项)。
  • m 获取无法解析方法getLayoutPosition
【解决方案2】:

这是在 kotlin 中的操作方法:

val layoutManager= GridLayoutManager(activity, 3)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int {
        return when (position) {
            0 -> 3
            else -> 1
        }
    }
}
recyclerView.layoutManager = layoutManager

这里,首先我们创建了一个 3 列的网格布局管理器,然后我们指定第一个将占据全部 3 列,而其余的只占用一列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2017-09-05
    • 1970-01-01
    • 2015-02-16
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多