Updated 30 November 2020
Android ViewPager allows the user to flip left and right through pages of contents. ViewPager found in the support library.
If you are using ViewPager for flipping static height layouts then you can simply add height flag as hardcoded like:
1 |
android:layout_height="300dp" |
If you want to use ViewPager for flipping the layouts having different heights then this blog will be helpful to you.
By adding WRAPCONTENT height flag for ViewPager will result in the ViewPager invisible this is because the wrap_content flag needs the height from the chield view which is not known in advance.
In this blog, we are using ViewPager for dynamic height views and the height of ViewPager will we updated dynamically at runtime based on the active layout height.
First, create a custom view pager class by extending ViewPager class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class EnhancedDynamicHeightViewPager : ViewPager { private var mCurrentView: View? = null constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var heightMeasureSpec = heightMeasureSpec if (mCurrentView == null) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) return } var height = 0 mCurrentView?.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) val h: Int = mCurrentView?.getMeasuredHeight()?:0 if (h > height) height = h heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) super.onMeasure(widthMeasureSpec, heightMeasureSpec) } fun measureCurrentView(currentView: View) { mCurrentView = currentView requestLayout() } } |
Now use this custom ViewPager in your layout xml file
1 2 3 4 5 |
<com.example.mycustomclass.EnhancedDynamicHeightViewPager android:id="@+id/carousel_banner_view_pager" android:layout_width="match_parent" android:layout_height="wrap_content" android:nestedScrollingEnabled="false" /> |
Till now we have created ViewPager with WRAPCONTENT height it will take the maximum height of your child’s view. Now we have to make the changes on the ViewPager adapter for changing the height of ViewPager as per our current active child view for this override the following method inside your ViewPager adapter:
1 2 3 4 5 6 7 8 9 10 11 |
private var mCurrentPosition = -1 override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) { super.setPrimaryItem(container, position, `object`) if (position != mCurrentPosition) { val pager: EnhancedDynamicHeightViewPager = container as EnhancedDynamicHeightViewPager mCurrentPosition = position pager.measureCurrentView(your child view) } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.