【问题标题】:Set last grid to full width using GridLayoutManager (RecyclerView)使用 GridLayoutManager (RecyclerView) 将最后一个网格设置为全宽
【发布时间】:2016-09-03 05:40:40
【问题描述】:

我使用RecyclerViewGridLayoutManager 以网格模式显示一些项目。它运行良好,并在网格内的 2 列中显示项目。

但是当项目数是奇数时,我希望最后一项必须是全宽(与RecyclerView 的宽度相同)。

有没有办法使用GridLayoutManager 或者我必须构建自定义设计?

请帮忙。

【问题讨论】:

    标签: android android-recyclerview gridlayoutmanager


    【解决方案1】:

    您可以使用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
    }
    

    继续构建更好的应用程序!

    【讨论】:

    • 为我节省了很多天的搜索时间。谢谢
    • 谁能帮忙。我正在尝试这个,但屏幕上只有一列。但是当我删除方法 setSpanSizeLookup 时,我总共得到 2 列。我正在努力实现与问题中提到的相同。我在网格中有 7 个项目,最后一个网格项目应该是填充宽度。提前致谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多