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

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

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

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

Solutions Collecting From Web of "RecyclerView LayoutManager不同的跨度计数在不同的行上"

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

如果你的网格项需要知道它的跨度大小,你可以在ViewHolderfind它:

  // 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());