How to manage empty span in GridLayoutManager?

1k views Asked by At

I am setting up contact directory in section recyclerview with grid layout manager, what my problem is that header is also set as an item in the span if the span is empty.

I tried using the SpanSizeLookup method. It's not working as I expected.

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

This is what I get

enter image description here

And this is what I really wants:

enter image description here

How to make header should be in next line with full width? Thank you.

1

There are 1 answers

1
Gustavo Pagani On

there is something with your code, I changed the code in onCreateView from Example1 to:

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

and it's working fine, this is the result:

result