如何使ViewPager高度wrap_content

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使ViewPager高度wrap_content相关的知识,希望对你有一定的参考价值。

我试图引用[https://medium.com/@nikhil4092/how-to-have-a-height-wrapping-viewpager-when-images-have-variable-heights-on-android-60b18e55e72e]这个链接来使viewpager的高度wrap_content但它没有用。我已经尝试了几个stackoverflow的问题,但没有一个可以解决我的问题。当我给出高度为wrap_content什么都没有显示

码:

public class HeightWrappingViewPager extends ViewPager {

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

public HeightWrappingViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int mode = MeasureSpec.getMode(heightMeasureSpec);
    // Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
    // At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
    if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
        // super has to be called in the beginning so the child views can be initialized.
        super.onMeasure(widthMeasureSpec, 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 has to be called again so the new specs are treated as exact measurements
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}

XML:

<com.project.test.HeightWrappingViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">

答案

我不确定它对你有帮助。 我使用下面的代码来显示不同高度的图像。 几乎像你的代码,但我像字段一样保存高度。

public class MeasuredViewPager extends ViewPager {

    private int mMaxHeight = 0;

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

    public MeasuredViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        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 > mMaxHeight) mMaxHeight = h;
        }

if (mMaxHeight != 0) heightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.EXACTLY);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

}

以上是关于如何使ViewPager高度wrap_content的主要内容,如果未能解决你的问题,请参考以下文章

如何将 Android ViewPager2 的高度包装到当前项目的高度?

具有不同项目高度和 WRAP_CONTENT 的 ViewPager2

如何使 ViewPager 和 gridview 同时垂直滚动

如何使 tablayout 片段适合 INSIDE viewpager

02ViewPager高度自适应轮播图

02ViewPager高度自适应轮播图