Display header as one row in Paging 3 library when we have GridLayoutManager

Viewed 337

I am trying to show header as one row in Paging3 library using GridLayoutManager. For the footer as one row, I made following implementation :

        val header = LoadStateAdapter { showAdapter.retry() }
        binding.list.apply {
            val layoutManager = layoutManager as GridLayoutManager
            layoutManager.spanSizeLookup = object : SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return if (showAdapter.getItemViewType(position) == ShowAdapter.LOADING_ITEM)
                        1 else layoutManager.spanCount
                }
            }
            adapter = showAdapter.withLoadStateHeaderAndFooter(
                header = header,
                footer = LoadStateAdapter { showAdapter.retry() }
            )
        }

And in the Adapter, I have following implementation :

override fun getItemViewType(position: Int): Int {
        return if (position == itemCount) SHOW_ITEM else LOADING_ITEM
    }

How about header? How can I display it in one row?

Full source code can be found here : https://github.com/alirezaeiii/Paging3-Sample

1 Answers
  1. override HeaderAdapter getStateViewType() method
  2. Create a ConcatAdapter use config
    fun withHeaderAndFooter(
        header: LoadStateAdapter<*>,
        footer: LoadStateAdapter<*>
    ): ConcatAdapter {
        addLoadStateListener { loadStates ->
            header.loadState = loadStates.prepend
            footer.loadState = loadStates.append
        }
        return ConcatAdapter(ConcatAdapter.Config.Builder().setIsolateViewTypes(false).build(), header, this, footer)
    }
  1. set layoutManager and override spanSizeLookup
val contactAdapter = adapter.withHeaderAndFooter(HeaderAdapter(), FooterAdapter())
layoutManager = GridLayoutManager(context, 2).apply {
    spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            return if (contactAdapter?.getItemViewType(position) in
                arrayOf(ADAPTER_FOOTER_TYPE,ADAPTER_HEADER_TYPE)
            ) spanCount else 1
        }

    }
}
Related