How to wrap the height of a ViewPager to the height of its current Fragment?

前端 未结 6 1538
轻奢々
轻奢々 2020-11-27 14:04

I made a ScrollView containing a ViewPager, but the ViewPager does not grow in height. When the content inside the ViewPager is too big, it get \'pucht\'(?) inside, the tabl

6条回答
  •  被撕碎了的回忆
    2020-11-27 14:35

    Finally found a better solution for WrapContentViewPager!

    The other solution contain some bug that hard to be solved, but I think this solution can be simply applied in our code

    I found it on this site https://github.com/akhahaha/burn-android/blob/master/app/src/main/java/com/ucla/burn/android/WrapContentViewPager.java

    Here is the code

    public class WrapContentViewPager extends ViewPager {
            public WrapContentViewPager(Context context) {
                super(context);
            }
    
            public WrapContentViewPager(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);
            }
        }
    

提交回复
热议问题