Solving ViewPager Height Issue Inside A Scrollview

Posted By : Daljeet Singh | 28-Mar-2018
More often than not we find ourselves creating a viewpager inside an activity in our android application, to hold fragments that contain a related set of data.The use of a viewpager in conjunction with a tab layout helps a user conveniently navigate between the fragments and perform the necessary actions.
 
 
 
A trivial use case scenario for a viewpager arises when it is used inside a parent scroll view in a layout.The view page doesn't seem to take up any space inside the scroll view even after assigning its height attribute value to wrap_content.This is caused by the viewpager calculating its height only when its child view is populated which happens after quite a bit of time of creation of the viewpager's view itself.Hence, the scroll view doesn't assign enough space in order to accommodate the views inside the viewpager.
 
 
 
The aforementioned issue can be fixed by creating a custom view pager which calculates its initial height based on the height of its first child view.
 
 
 
The customviewpager will extend Viewpager class and implement constructors so that it can be called inside the layout XML :
 
public class CustomViewPager extends ViewPager {
public CustomViewPager(@NonNull Context context) {
        super(context);
    }
 
    public CustomViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
We need to override the onMeasure method for the customviewpager, in order for it to take up appropriate height based on its child views.The customviewpager will measure the height of its first child(usually at position 0) and set its height equal to that value :
 
@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        try {
    int currentPagePosition=0;
            View child = getChildAt(currentPagePosition);
            if (child != null) {
                child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                int h = child.getMeasuredHeight();
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
Now we just need to replace the viewpager in our layout.xml with the CustomViewPager that we have just created and we are good to go.

About Author

Author Image
Daljeet Singh

Daljeet has experience developing android applications across a range of domains such as Cryptocurrency, Travel & Hotel Booking, Video Streaming and e-commerce. In his free time, he can be found playing/watching a game of football or reading up on either

Request for Proposal

Name is required

Comment is required

Sending message..