Dynamic height viewpager

后端 未结 6 1346
無奈伤痛
無奈伤痛 2020-11-27 13:06

I\'m trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child\'s height.

package com.example.vihaan.dynamicviewp         


        
6条回答
  •  独厮守ぢ
    2020-11-27 13:53

    Made a few tweaks in your code and it is working fine now.

    1] onMeasure function wasn't proper. Use below logic

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mCurrentView == null) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        int height = 0;
        mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        int h = mCurrentView.getMeasuredHeight();
        if (h > height) height = h;
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    

    2] ViewPager needs to be re-measured each time a page is changed. Good place to do this is setPrimaryItem function of PagerAdapter

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

    Here is the link to GitHub project with these tweaks: https://github.com/vabhishek/WrapContentViewPagerDemo

提交回复
热议问题