fragment自适应高度问题

需求是在ScrollView中嵌套ViewPager,每个fragment中高度不同

步骤:

    1,自定义viewpager重写onMeasure方法

@Override

protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //高度自适应处理

        View view = getChildAt(getCurrentItem());

        if (view !=null) {

        view.measure(widthMeasureSpec, heightMeasureSpec);

        }

        setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, view));

}

/**

* Determines the height of this view

* @param measureSpec A measureSpec packed into an int

* @param view the base view with already measured height

* @return The height of the view, honoring constraints from measureSpec

*/

private int measureHeight(int measureSpec, View view) {

    int result =0;

    int specMode = MeasureSpec.getMode(measureSpec);

    int specSize = MeasureSpec.getSize(measureSpec);

    if (specMode == MeasureSpec.EXACTLY) {

    result = specSize;

    }else {

    // set the height from the base view if available

        if (view !=null) {

            result = view.getMeasuredHeight();

        }

        if (specMode == MeasureSpec.AT_MOST) {

        result = Math.min(result, specSize);

        }

    }

    return result;

}

2,在代码中调用

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override

            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            @Override

            public void onPageSelected(final int position) {

            // 切换到当前页面,重置高度

              mViewPager.requestLayout();

            }

            @Override

            public void onPageScrollStateChanged(int state) { }

        });

最后一定要设置viewPager.setOffscreenPageLimit(adapter.getCount());

文章来源:

https://blog.csdn.net/u013626215/article/details/79866050

你可能感兴趣的:(fragment自适应高度问题)