ViewPager series: ViewPager adaptive content height

  • There are fragments in ViewPager, and the layout_height of ViewPager is set to wrap_content. If three modules are arranged vertically in the Fragment, one of the modules needs to be hidden. After the code is hidden, the height value of the Fragment will become smaller, and there will be a blank at the bottom.

  • That is to say, although the wrap_content is set for the ViewPager height, there is no adaptive height, and onMeasure() needs to be rewritten. There is not much BB, and the code.

public class CannotScrollViewPager extends ViewPager {


    public CannotScrollViewPager(@NonNull Context context) {
        this(context, null);
    }

    public CannotScrollViewPager(@NonNull Context context, @Nullable 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);
    }

}

  • The principle has not been studied in depth, and the description of the MeasureSpec.makeMeasureSpec() function will be added later.

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/114869542