如何在GridLayoutManager中管理空跨度?

时间:2017-08-29 05:33:12

标签: android android-recyclerview gridlayoutmanager sectionedrecyclerviewadapter

我正在使用网格布局管理器设置部分recyclelerview中的联系人目录,我的问题是如果跨度为空,则标题也会设置为跨度中的项目。

我尝试使用SpanSizeLookup方法。它没有像我预期的那样工作。

layoutManager = new GridLayoutManager(getActivity(), 3);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch(adapterDocument.getItemViewType(position)){
                    case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                        return 3;

                    case SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED:
                        return 1;
                    default:
                        return 1;
                }
            }
        });

这就是我得到的

enter image description here

这就是我真正想要的:

enter image description here

如何制作标题应该在下一行全宽?谢谢。

1 个答案:

答案 0 :(得分:1)

您的代码有所改变,我将onCreateView中的代码从Example1更改为:

    sectionAdapter = new SectionedRecyclerViewAdapter();

    for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) {
        List<String> contacts = getContactsWithLetter(alphabet);

        if (alphabet == 'B' || alphabet == 'D') {
            contacts = Collections.emptyList();
        }

        if (contacts.size() > 0) {
            sectionAdapter.addSection(new ContactsSection(String.valueOf(alphabet), contacts));
        }
    }

    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
    GridLayoutManager glm = new GridLayoutManager(getContext(), 3);
    glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            switch(sectionAdapter.getSectionItemViewType(position)) {
                case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                    return 3;
                default:
                    return 1;
            }
        }
    });
    recyclerView.setLayoutManager(glm);
    recyclerView.setAdapter(sectionAdapter);

它工作正常,结果如下:

result