Nov 4 · 1 min read
Thank you for sharing your investigations in this great write-up!
As we implemented your suggestions, we had the idea to extend ViewPager2 with these features. This did not work, as ViewPager2 is final. So we considered a Decorator, but discarded the idea as this might have gotten out of hands quickly. Finally, we added an extension function to encapsulate all those changes:
/**
* ViewPager2 workarounds documented at https://itnext.io/android-viewpager2-with-pretty-page-margin-bfae8dd397a8
*/
fun ViewPager2.setMarginDrawable(@DrawableRes resId: Int) {
/*
* Two assumptions:
* 1. <ViewPager2> will continously use <RecyclerView> to display its content.
* 2. <ViewPager2> will only have one instance of <RecyclerView>.
*/
(children.find { it is RecyclerView } as? RecyclerView)?.let {recyclerView ->
recyclerView.clipChildren = false
val divider = DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL)
divider.setDrawable(resources.getDrawable(resId, null))
recyclerView.addItemDecoration(divider)
recyclerView.overScrollMode = ConstraintLayout.OVER_SCROLL_NEVER
offscreenPageLimit = 1
clipChildren = false
clipToPadding = false
} ?: LogUtils.e("ViewPager2.setMarginDrawable", "Failed to access ViewPager2 RecyclerView")
}