How to wrap height of Android ViewPager2 to height of current item? How to wrap height of Android ViewPager2 to height of current item? android android

How to wrap height of Android ViewPager2 to height of current item?


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.


I'm not at all happy with this workaround, but it does solve the rendering problems I had when trying to use ViewPager2 with fragments of different heights. It will obviously slow down rendering and consume more memory.

myStupidViewPager2.offscreenPageLimit = fragments.size


I had the same problem, ViewPager2 was in ScrollView, which is under TabLayout. After navigating through the tabs, the height of the ScrollView became equal to the height of the maximum fragment height.The problem was solved by transferring the ScrollView to the fragment.