本文介绍了RecyclerView LayoutManager 在不同的行上有不同的跨度计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个 RecyclerView.LayoutManager
,它允许我为不同的行指定不同的跨度计数作为重复模式.例如,包含 10 个项目的 2,3 将如下所示:
I want a RecyclerView.LayoutManager
that allows me to specify different span counts for different rows as a repeating pattern. For example 2,3 with 10 items would look like this:
-------------
| | |
| | |
-------------
| | | |
| | | |
-------------
| | |
| | |
-------------
| | | |
| | | |
-------------
我可以想出一种使用 GridLayoutManager
和 SpanSizeLookup
来破解这个问题的方法,但有人想出更简洁的方法来做到这一点吗?
I can think of a way to hack this with GridLayoutManager
and SpanSizeLookup
but has anybody come up with a cleaner way to do this?
推荐答案
要做你想做的事,你可能必须自己编写LayoutManager
.
To do what you want, you probably have to write your own 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());
这篇关于RecyclerView LayoutManager 在不同的行上有不同的跨度计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!