Created
April 29, 2020 18:00
-
-
Save thevoiceless/6ec108e821629ecd779703d877f0fe18 to your computer and use it in GitHub Desktop.
ViewPager2 OnPageChangeCallback that tracks the percentage visibility for each page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object : ViewPager2.OnPageChangeCallback() { | |
private var settledOnPage = 0 | |
private var idle = true | |
val percentages = MutableList(adapter!!.itemCount) { 0f } | |
.apply { set(0, 1f) } | |
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { | |
Timber.i("${1f - positionOffset} of page ${position + 1} is visible") | |
if (!idle && settledOnPage < position + 1) { | |
Timber.i("Dragging left $positionOffset, ${1f - positionOffset} of index ${position} is visible") | |
percentages[position] = 1f - positionOffset | |
if (position < percentages.size - 1) percentages[position + 1] = positionOffset | |
if (positionOffset == 0f && position > 1) percentages[position - 1] = 0f | |
Timber.i(percentages.joinToString(separator = " ") { "[%.2f]".format(it) }) | |
notifyObservers(percentages) | |
} else if (settledOnPage == position + 1) { | |
Timber.i("Dragging right $positionOffset") | |
percentages[position + 1] = positionOffset | |
percentages[position] = 1f - positionOffset | |
if (positionOffset == 0f && position < percentages.size - 1) percentages[position + 1] = 0f | |
Timber.i(percentages.joinToString(separator = " ") { "[%.2f]".format(it) }) | |
notifyObservers(percentages) | |
} | |
notifyObservers(percentages) | |
} | |
override fun onPageScrollStateChanged(state: Int) { | |
when (state) { | |
ViewPager2.SCROLL_STATE_IDLE -> { | |
settledOnPage = currentItem | |
idle = true | |
Timber.i("Idle on $settledOnPage") | |
} | |
ViewPager2.SCROLL_STATE_DRAGGING -> { idle = false } | |
ViewPager2.SCROLL_STATE_SETTLING -> { idle = false } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment