Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewPager with dynamic height

I have a ViewPager to show some Fragments and swipe between them but the height of the ViewPager is dynamic based on the content. Assume I have multiple list that each list placed in one tab and by changing tabs the height of ViewPager should change properly I created a custom ViewPager and overrided onMeasure but the problem is ViewPager creates the next fragment sooner that current fragment (visible one) gets It's height from next fragment measure.

Here is MyViewPager :

public class MyViewPager extends ViewPager {

    public MyViewPager(Context context) {
        super(context);
    }
    
    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = 0;
        for(int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(
                widthMeasureSpec,
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
            );
            int h = child.getMeasuredHeight();
            if(h > height) height = h;
        }
    
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    
}

I also tried to trigger onMeasure method of MyViewPager when the fragment become visible like below but nothing changes.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        PostDetailsActivity activity = (PostDetailsActivity) getActivity();
        activity.pagerParent.requestLayout();
        activity.pagerParent.invalidate();
    }
}
like image 269
Hamidreza Salehi Avatar asked Feb 06 '16 15:02

Hamidreza Salehi


1 Answers

I found a good solution here If anyone else was wondering how to make ViewPager change It's height dynamically.

Also you can find quick answer here If you don't have time to look at Git.

like image 151
Hamidreza Salehi Avatar answered Nov 02 '22 21:11

Hamidreza Salehi