使用GridLayoutManager (RecyclerView)设置最后一个网格为全宽度



我使用RecyclerViewGridLayoutManager在网格模式中显示一些项目。它工作得很好,并在网格内的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
}

继续开发更好的应用!

最新更新