我使用RecyclerView
与GridLayoutManager
在网格模式中显示一些项目。它工作得很好,并在网格内的2列中显示项目。
但是当项目的数量是奇数时,我希望最后一个项目必须是全宽度的(与RecyclerView
的宽度相同)。
是否有办法使用GridLayoutManager
或我必须建立自定义设计?
请帮。
您可以从GridLayoutManager
中使用layoutManager.setSpanSizeLookup
方法
下面是使用
的方法final GridLayoutManager layoutManager = new GridLayoutManager(context, 2);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (mAdapter != null) {
switch (mAdapter.getItemViewType(position)) {
case 1:
return 1;
case 0:
return 2; //number of columns of the grid
default:
return -1;
}
} else {
return -1;
}
}
});
现在你必须确定adapter
viewType
@Override
public int getItemViewType(int position) {
return (position == getItemCount() - 1) ? 0 : 1; // If the item is last, `itemViewType` will be 0
}
继续开发更好的应用!