解決在scrollview中的viewpager高度自適應的問題

package com.ysd.keepcar.view.shop.model;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;

public class CustomViewPager extends ViewPager {

    public CustomViewPager(Context context) {
        super(context);
    }

    public CustomViewPager(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);
    }
}

 

 

 

 

 

public class AutoHeightViewPager extends ScrollableViewPager {

    private final int mTmpHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);

    private int mTmpIndex;
    private int mTmpHeight;
    private View mTmpChild;

    public AutoHeightViewPager(@NonNull Context context) {
        super(context);
    }

    public AutoHeightViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
                getDefaultSize(0, heightMeasureSpec));
        mTmpHeight = 0;
        for (mTmpIndex = 0; mTmpIndex < getChildCount(); mTmpIndex++) {
            mTmpChild = getChildAt(mTmpIndex);
            measureChild(mTmpChild, widthMeasureSpec, mTmpHeightSpec);
            mTmpHeight = mTmpHeight > mTmpChild.getMeasuredHeight() ? mTmpHeight :
                    mTmpChild.getMeasuredHeight();
        }

        setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(mTmpHeight,
                MeasureSpec.EXACTLY));
    }
}
相關文章
相關標籤/搜索