使用SpanSizeLookup为GridLayoutManager中的项设置范围

Igo*_*pov 84 android android-support-library gridlayoutmanager android-recyclerview

我想用节标题实现类似网格的布局.想想https://github.com/TonicArtos/StickyGridHeaders

我现在应该做什么:

mRecyclerView = (RecyclerView) view.findViewById(R.id.grid);
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch(mAdapter.getItemViewType(position)){
                    case MyAdapter.TYPE_HEADER:
                        return 1;
                    case MyAdapter.TYPE_ITEM:
                        return 2;
                    default:
                        return -1;
                }
            }
        });

mRecyclerView.setLayoutManager(mLayoutManager);
Run Code Online (Sandbox Code Playgroud)

现在常规项和标题的跨度大小为1.我该如何解决这个问题?

Igo*_*pov 143

问题是标题的跨度大小应为2,常规项的跨度大小应为1.所以正确的实现是:

mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch(mAdapter.getItemViewType(position)){
                    case MyAdapter.TYPE_HEADER:
                        return 2;
                    case MyAdapter.TYPE_ITEM:
                        return 1;
                    default:
                        return -1;
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

  • 获取跨度大小的方法确定您的单元格将采用的跨度宽度,而不是col行的数量应该具有的!! (12认同)

And*_*per 28

标题的跨度应等于整个列表的跨度计数.

mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
           switch(mAdapter.getItemViewType(position)){
                    case MyAdapter.TYPE_HEADER:
                        return mLayoutManager.getSpanCount();
                    case MyAdapter.TYPE_ITEM:
                        return 1;
                    default:
                        return -1;
                }
    }
});
Run Code Online (Sandbox Code Playgroud)