RecyclerView LayoutManager不同的跨度计数在不同的行上

时间:2015-06-29 09:33:26

标签: android android-recyclerview

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

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

我可以想办法用GridLayoutManagerSpanSizeLookup来解决这个问题,但是有人想出一个更干净的方法吗?

2 个答案:

答案 0 :(得分:49)

要做你想做的事,你可能需要自己编写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());

答案 1 :(得分:0)

这是在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列,而其余仅占据一列。