Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 276
ban-geoengineering Avatar asked Aug 28 '19 13:08

ban-geoengineering


People also ask

How do you wrap the height of a ViewPager to the height of its 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.

What is difference between ViewPager and ViewPager2?

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 .


1 Answers

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.

like image 87
Lucas Nobile Avatar answered Sep 27 '22 20:09

Lucas Nobile