Categories
Studio

ViewPager — Resize with every page | by Saurabh Pant | May, 2021

Saurabh pants

It’s good to adjust from time to time.

Normally, when you use a view pager, all views try to fit in the specified dimension. This is fine for most scenarios, but what about focusing on the view pager and adjusting the screen for each view? Something like the image below:

Content shifts up and down according to image height

As you can see, when you focus on an image that is taller than the previous image, the action buttons and content below it shift down, and vice versa. Now let’s dive directly into the code and do this.

Step 1: Create a class AdjustingViewPager (obviously you can give it any name) that extends ViewPager.

class AdjustingViewPager: ViewPager {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
}

Step 2: Override onMeasure Callback as follows

Let’s understand what this does.

1) Check if the view has dimensions assigned by its parent. If it is in one of the Measure Specs.Unspecified or Measure Spec.At best Mode means that the view can be of any dimension and confirms the current view.

2) If currentView is not null, extract the measured height.

3) If the height of the currentView is greater than the height allowed in pixels, simply set it to allowedHeight and pass the final width and height to.

super.onMeasure(widthMeasureSpec, newViewHeight)

Step 3: Create a method in the AdjustingViewPager class

fun measureCurrentView(view: View) {
this.currentView = view
requestLayout()
}

This method simply captures the current view in focus, updates the view pager layout, and requests it to resize according to the size of the new view.

Step 4: Within the ImagePagerAdapter class, override the following method as follows:

override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
super.setPrimaryItem(container, position, `object`)
if (container !is AdjustingViewPager)
return
if (position != currentPosition) {
val viewPager: AdjustingViewPager = container
currentPosition = position;
viewPager.measureCurrentView(`object` as View)
}
}

This method checks if the current view has focus and then updates it to the view pager to resize it.

And that’s it. You can now use the AdjustingViewPager as a regular view pager for your layout, as follows:

<com.aqua30.learningproject.AdjustingViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

The final output above is:

If its helpful then im happy.

Check out the full code gist https://gist.github.com/aqua30/b7da69fc8d78c0b117a1fb6dd5bc1d00

Continue coding.

cheers!

Source

Leave a Reply

Your email address will not be published. Required fields are marked *