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

ale*_*ett 27 android android-recyclerview

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

  -------------
  |     |     |
  |     |     |
  -------------
  |   |   |   |
  |   |   |   |
  -------------
  |     |     |
  |     |     |
  -------------
  |   |   |   |
  |   |   |   |
  -------------
Run Code Online (Sandbox Code Playgroud)

我能想到的方法与破解这个GridLayoutManagerSpanSizeLookup,但已经有人想出了一个更清洁的方式做到这一点?

kri*_*son 55

要做你想做的事,你可能要写自己的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");
        }
    });
Run Code Online (Sandbox Code Playgroud)

如果您的网格项需要知道其跨度大小,您可以在以下内容中找到它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());
Run Code Online (Sandbox Code Playgroud)


Ami*_*ian 7

这是在 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
Run Code Online (Sandbox Code Playgroud)

在这里,首先我们创建了一个包含 3 列的网格布局管理器,然后我们指定第一个将占据整个 3 列,而其余的仅占据一列。