ViewPager in a NestedScrollView

前端 未结 19 2073
面向向阳花
面向向阳花 2020-11-27 10:08

I need to create an interface like Google Newsstand which is a sort of ViewPager (horizontal scroll) over a collapsing header (vertical scroll). One of my requirements is to

19条回答
  •  粉色の甜心
    2020-11-27 10:44

    Use below customized class to resolve your problem. Don't forget to call onRefresh() method on pagechangelistener.

    public class ContentWrappingViewPager extends ViewPager
    {
        private int width = 0;
        public ContentWrappingViewPager(Context context) {
            super(context);
        }
    
        public ContentWrappingViewPager(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            int height = 0;
            width = widthMeasureSpec;
            if (getChildCount() > getCurrentItem()) {
                View child = getChildAt(getCurrentItem());
                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);
        }
    
        public void onRefresh()
        {
            try {
                int height = 0;
                if (getChildCount() > getCurrentItem()) {
                    View child = getChildAt(getCurrentItem());
                    child.measure(width, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                    int h = child.getMeasuredHeight();
                    if(h > height) height = h;
                }
    
                int heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
                ViewGroup.LayoutParams layoutParams = this.getLayoutParams();
                layoutParams.height = heightMeasureSpec;
                this.setLayoutParams(layoutParams);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题