Set span for items in GridLayoutManager using SpanSizeLookup

不羁岁月 提交于 2019-12-17 04:46:52

问题


I want to implement grid-like layout with section headers. Think of https://github.com/TonicArtos/StickyGridHeaders

What I do now:

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);

Now both regular items and headers have span size of 1. How do I solve this?


回答1:


The problem was that header should have span size of 2, and regular item should have span size of 1. So correct implementations is:

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;
                }
            }
        });



回答2:


Header should have a span equal to the span count of the entire list.

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;
                }
    }
});



回答3:


Answer to my own question: Override the getSpanSizeLookup() from the Activity after setting the adapter.



来源:https://stackoverflow.com/questions/26869312/set-span-for-items-in-gridlayoutmanager-using-spansizelookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!