android kotlin what is the current way of make sure viewPager2 pageItem resume is fired only when onscreen?

114 views Asked by At

I want init tasks (starting a countDownTimer) only when the viewPager2 pages become visible. and stop timer when they get off-screen. however, I got stuck on the fact that resume() is fired when off-screen for pageItem.

setUserVisibleHint seems deprecated, it seems sexMaxLifeCycle is current way, however, I am not sure how this can be called, not sure whether call it within... and onHiddenChanged() does not work either.

class ToneFragmentStateAdapter(activity:FragmentActivity):FragmentStateAdapter(activity){

fun setItems(newItems: List<Tone4>) {
    _items = newItems
    notifyDataSetChanged()
}

private var _items = listOf<Tone4>()

override fun getItemCount(): Int = _items.size

override fun createFragment(position: Int): Fragment
= TonePageFragment.newInstance(position, _items[position])}
1

There are 1 answers

1
Benjamin Cassidy On

ViePager2 creates and attaches fragments off-screen for performance reasons. What you could do is implement a ViewPager2.OnPageChangeCallback and then have a method on your fragment that tells it is the currently active fragment.

For example

fun onPageSelected(position int) {
   adapter.items.forEachIndexed( index, fragment -> {
       fragment.setActive(position == index)
   }
}