This question is for the new ViewPager2 class.
There is a similar question for the old ViewPager, but the solution requires extending ViewPager. However, ViewPager2 is final so cannot be extended.
In my situation, I have a ViewPager2 that contains three different fragments. One of these fragments is much taller than the other two, which means when you swipe to one of the shorter fragments, there is a lot of empty space. So how do I effectively wrap the ViewPager2 to the height of the current fragment?
To solve this, rather than calling viewPager. setOffscreenPageLimit(2) , I simply replaced View child = getChildAt(getCurrentItem()); in the above code with Fragment childFragment = (Fragment)getAdapter(). instantiateItem(this, getCurrentItem()); View child = childFragment.
ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .
The solution is to add the following in each fragment that is part of the ViewPager2
:
override fun onResume() {
super.onResume()
binding.root.requestLayout()
}
binding.root
is from ViewBinding/DataBinding but it's is the main container of your layout, i.e. ConstraintLayout
, LinearLayout
, etc.
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