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

前端 未结 6 1539
轻奢々
轻奢々 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 14:21

    in my case, i created imageslider with viewpager. initial value of child is null also at the end of index, value of child is null. so, i made some upgrades for repitch answer, because it didn't handle (child==null)

    ViewPager now looks like:

    public class WrapContentViewPager extends ViewPager {
    
        public WrapContentViewPager(Context context) {
            super(context);
            initPageChangeListener();
        }
    
        public WrapContentViewPager(Context context, AttributeSet attrs) {
            super(context, attrs);
            initPageChangeListener();
        }
    
        private void initPageChangeListener() {
            addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    requestLayout();
                }
            });
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            View child = getChildAt(getCurrentItem());
            if (child != null) {
                child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                int h = child.getMeasuredHeight();
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
            } else {for(int i = 0; i < getChildCount(); i++) {
                    View child2 = getChildAt(i);
                    child2.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                    int h = child2.getMeasuredHeight();
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
            }}
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    
    }
    

    also, you can add amount of height whatever you want, if the last item of viewpager stick to circlepageindicator, like this : int h = child2.getMeasuredHeight()+50;

提交回复
热议问题