4

I'd like to use a ViewPager with paging library and PagedList. Is there a way to do this? If yes then what adapter should I use?

Right now I use FragmentStatePagerAdapter with a full list of items. I'd like to load pages of items on demand instead of loading all the data at once.

Bartek
  • 1,327
  • 1
  • 11
  • 22

2 Answers2

3

This is what I'm currently playing with. I've seen it paging, but I need to write some tests to ensure this is actually offering any benefits. Still a lot of room for improvements, but I think this is the core necessary for it to function.

This requires that you .setInitialLoadKey on the PageList. I wasn't able to get it to respond to something like .smoothScrollToPosition. It's working in an image viewer atm.

abstract class PagedListPagerAdapter<T>(fm: FragmentManager)
    : FragmentStatePagerAdapter(fm) {

    var pagedList: PagedList<T>? = null
        private set
    private var callback = PagerCallback()

    override fun getCount() = pagedList?.size ?: 0

    abstract fun createItem(position: Int): Fragment

    abstract var isSmoothScroll: Boolean

    override fun getItem(position: Int): Fragment {
        pagedList?.loadAround(position)
        return createItem(position)
    }

    fun getValue(position: Int): T? {
        return pagedList?.get(position)
    }

    fun submitList(pagedList: PagedList<T>?) {
        this.pagedList?.removeWeakCallback(callback)
        this.pagedList = pagedList
        this.pagedList?.addWeakCallback(null, callback)
        notifyDataSetChanged()
    }

    private inner class PagerCallback : PagedList.Callback() {
        override fun onChanged(position: Int, count: Int) = notifyDataSetChanged()
        override fun onInserted(position: Int, count: Int) = notifyDataSetChanged()
        override fun onRemoved(position: Int, count: Int) = notifyDataSetChanged()
    }
}

class ViewerAdapter(fm: FragmentManager)
    : PagedListPagerAdapter<ImageInfo>(fm) {

    override var isSmoothScroll = false

    override fun createItem(position: Int): Fragment {
        val fragment = ViewPagerFragment()
        fragment.source = getValue(position)
        return fragment
    }
}
Anthony
  • 7,638
  • 3
  • 38
  • 71
0

I used FragmentStateAdapter with PagedList by following this blog https://medium.com/@programmerr47/pagedlist-in-viewpager-976e7413ec46

The hack is you create a class/abstract class extending FragmentStateAdapter or ViewPager or any similar class as per your functionality and adding PagedList to it. Then another class inheriting/implementing it.

Call submitList (our custom method) on this second class object and you'll need to handle the rest. This blog, though, makes good use of resources and callbacks to make this efficient.

Remember that you cannot access the PagedList's contents directly so don't waste time around that

Damanpreet Singh
  • 678
  • 10
  • 15