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);
    }
}  
posted @ 2016-05-10 18:20  Yusuzhan  阅读(2466)  评论(0编辑  收藏  举报
Fork me on GitHub