Android ViewPager无法使用wrap_content属性自适应高度


使用ViewPager的时候发现一个问题,当设置ViewPager控件的height属性为wrap_content时,控件高度一直是0,无法正常显示,在网上找到了解决办法,重写ViewPager的onMesure()方法.

public class WrapContentHeightViewPager extends ViewPager {
    /**
     * Constructor
     *
     * @param context
     *            the context
     */
    public WrapContentHeightViewPager(Context context) {
        super(context);
    }
    /**
     * Constructor
     *
     * @param context
     *            the context
     * @param attrs
     *            the attribute set
     */
    public WrapContentHeightViewPager(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);
    }
}  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM