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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With