GridLayoutManager setSpanSizeLookup 不工作

GridLayoutManager setSpanSizeLookup not working

我将 GridLayoutManager 与 2 个单元格一起使用,对于某些单元格,我希望跨度为一个单元格,因此我尝试使用 setSpanSizeLookup,但它不起作用。我尝试为所有位置返回跨度计数 1,但仍然出现两个单元格而不是一个单元格。

以下是我的代码

gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            return 1;
        }
    });
    recyclerView.setLayoutManager(gridLayoutManager);

有什么不工作的原因吗?

替换

return 1;

return 2;

这指定您将 2 个单元格合并为 1 个单元格。

代码

这是我为特定位置跨越 2 个单元格的代码

GridLayoutManager glm=new GridLayoutManager(mContext,2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            switch(categoryAdapter.getItemViewType(position)) {
                case 1:
                    return 2;
                default:
                    return 1;
            }
        }
    });
    mRecyclerViewCategory.setLayoutManager(glm);

如何在 Recycler Adapter

中定义案例跨度
@Override
public int getItemViewType(int position) {
    if(position==[your_specific_postion_where_to_span]){
        return 1;
    }
    return super.getItemViewType(position);
}

我为此苦苦挣扎,因为目前这里的文档很差。我是这样想的...

getSpanSize 和 getSpanIndex 似乎可以一起使用。对我来说,我试图在跨越两列的 gridlayoutManager 中插入一个 pageViewer。所以它被定义为:mGridLayout = new GridLayoutManager(getActivity(), 2);

//must be called before setLayoutManager is invoked
private void setNumOfColumnsForPageViewer(final FallCollectionRecyclerAdapter adapter) {

    mGridLayout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (adapter.getItemViewType(position) == MyRecyclerAdapter.TYPE_PAGE_VIEWER)
                return 2; //some other form of item like a header, or whatever you need two spans for
            else
                return 1; //normal item which will take up the normal span you defined in the gridlayoutmanager constructor
        }

        @Override
        public int getSpanIndex(int position, int spanCount) {
            if (adapter.getItemViewType(position) == FallCollectionRecyclerAdapter.TYPE_PAGE_VIEWER)
                return 1;//use a single span
            else
                return 2; //use two spans
        }
    });

    mRecyclerView.setLayoutManager(mGridLayout);
}