shihyingru
6/30/2017 - 6:45 AM

#viewpager_autosize

#viewpager_autosize

##viewpager_autosize

viewpager 高度自適應
(https://stackoverflow.com/questions/8394681/android-i-am-unable-to-have-viewpager-wrap-content)
(https://ddnews.me/tech/v40eh21g.html)


+動態計算高度,通過LayoutParmas改變ViewPager的高度,或者在onMeasure中返回childView的高度。 網上大部分的解決方法是通過下面的方法。

    public class CustomViewPager extends ViewPager {
        private View view;
        public CustomViewPager(Context context) {
        super(context);
    }
        public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
        @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            if(view == null){
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
            int height = 0;
        view.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        int h = view.getMeasuredHeight();
            if(h > height) height = h;
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
        public void measureCurrentView(View currentView){
        view = currentView;
        requestLayout();
    }
        public int measureFragment(View view){
        if(view == null) return 0;
            view.measure(0, 0);
        return view.getMeasuredHeight();
    }
}

之後在viewpager控制頁面覆寫viewpagerAdpater的setPrimaryItem Method.

@Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        if(position != currentPosition){
            Fragment fragment = (Fragment) object;
            CustomViewPager pager = (CustomViewPager) container;
            if(fragment != null && fragment.getView() != null){
                currentPosition = position;
                pager.measureCurrentView(fragment.getView());
            }
        }
    }