解決ViewPager根據試圖動態調整高度

兩個問題

1.在使用ViewPager組件設置高度爲wrap_content佈局時,會出現View不顯示的問題;

2.在使用WrapContentViewPager時,pager的子頁面高度一致,導致頁面內容少的view出現空白;

解決第一個問題,直接下載WrapContentViewPager到項目中使用即可。但是會出現第二個問題;原因是,在WrapContentViewPager中複寫OnMeasure方法,使用的高度是子頁面中最大的高度,所以頁面內容少的view會出現空白

解決第二個問題,動態改變pager的高度即可


/**
 * ViewPager DynamicHeight解決方案
 */
public class DynamicHeightViewPager extends ViewPager {


    /**
     * Constructor
     *
     * @param context the context
     */
    public DynamicHeightViewPager(Context context) {
        super(context);
    }

    /**
     * Constructor
     *
     * @param context the context
     * @param attrs   the attribute set
     */
    public DynamicHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //    @Override
//    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//
//        // find the first child view
//        View view = getChildAt(0);
//        if (view != null) {
//            // measure the first child view with the specified measure spec
//            view.measure(widthMeasureSpec, heightMeasureSpec);
//        }
//
//        setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, view));
//    }
    /**
     * 解決pager中視圖高度不一致的情況 動態更改pager高度
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(final int widthMeasureSpec, int heightMeasureSpec) {
        int index = getCurrentItem();
        int height = 0;
        View v = getChildAt(index);
        if (v != null) {
            v.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            height = v.getMeasuredHeight();
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + 80, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        final ViewPager pager = this;
        pager.addOnPageChangeListener(new SimpleOnPageChangeListener() {
            private int position;
            private int oldPositon;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                this.position = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == 2) {
                    requestLayout();
                }
            }

        });
    }
}

 

發佈了105 篇原創文章 · 獲贊 15 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章