Android RecyclerView和GridLayoutManager使项目跨越多行
我有一组照片,我正在使用RecyclerView
来显示它们。我想让我的RecyclerView
中的第一个元素跨越两列和两行:
我知道我可以用setSpanSizeLookup
跨越两列:
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position == 0) {
return 2;
} else {
return 1;
}
}
});
但是如何使第一项也跨越两行呢强>
我曾尝试通过将不同的布局膨胀到其他布局的两倍高度,将第一个项目的高度设置为不同,但这导致与第一个项目位于同一行的每个项目也被拉伸到该高度:
@Override
public ProfilePicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == TYPE_MAIN_PHOTO) {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_main_profile_photo, parent, false);
} else {
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_profile_photo, parent, false);
}
return new ProfilePicViewHolder(itemView);
}
# 1 楼答案
您可以使用Arastel在here中编写的SpandGridLayoutManager库
这就是结果
# 2 楼答案
通过仅对行使用RecycleView,并对每行使用ViewHolder,可以实现此行为。因此,对于简单的行,您可以使用RowViewHolder,对于自定义布局,您可以使用DoubleRowViewHolder,它将有3个项目,这正是您想要的方式
# 3 楼答案
使用GridLayoutManager无法实现此行为,因为它只支持跨多个列
Nick Butcher目前正在实现一个定制的SpandGridLayoutManager,它完全满足您的需求。它允许您同时跨越多个行和列。实现仍然是WIP,但已经运行得很好
我是一名布局经理。爪哇
attrs。xml
代码也可以在here中找到
示例用法
该代码要求RecyclerView 23.2.0或更高版本。 因此,在你的构建中添加以下行。格雷德尔,如果你还没这么做的话
为了实现初始帖子中显示的布局,我们将LayoutManager定义如下