Viewpager with dynamic height not working (always use the first fragment's height)

前端 未结 2 795
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 16:39

I have followed this and that answers, i also found this link.

I use those resources to do trial & errors. Now my custom ViewPager successfully measure

2条回答
  •  名媛妹妹
    2021-02-04 17:18

    public CustomPager (Context context) {
        super(context);
    }
    
    public CustomPager (Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    int getMeasureExactly(View child, int widthMeasureSpec) {
        child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        int height = child.getMeasuredHeight();
        return MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }
    
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
    
        final View tab = getChildAt(0);
        if (tab == null) {
            return;
        }
    
        int width = getMeasuredWidth();
        if (wrapHeight) {
            // Keep the current measured width.
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
        }
        Fragment fragment = ((Fragment) getAdapter().instantiateItem(this, getCurrentItem()));
        heightMeasureSpec = getMeasureExactly(fragment.getView(), widthMeasureSpec);
    
        //Log.i(Constants.TAG, "item :" + getCurrentItem() + "|height" + heightMeasureSpec);
        // super has to be called again so the new specs are treated as
        // exact measurements.
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    

提交回复
热议问题