Jan Michael Kolbe
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")
}
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade