1

I have viewpager that contains 3 fragment, in those fragments there is no imageview but just simple cells. When I am switching to longer fragment (recyclerview has more items) viewpager is lagging.

I record video for better understanding : https://youtu.be/6IMzItswBGo

And my custom viewpager for adjusting height of pages.

public class CustomPager extends ViewPager
{
    private int width = 0;
    public CustomPager(Context context) {
        super(context);
    }

    public CustomPager(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();
        }
    }
}

I'm using that Dynamic height viewpager

Emre Akcan
  • 982
  • 10
  • 27

2 Answers2

3

Use this code to preload all 3 fragments while setting viewpager adapter.

 viewPager.setOffScreenPageLimit(3);
Roshaan Farrukh
  • 399
  • 3
  • 10
0

It seems that it takes too much time in onMeasure() method. I wonder why you want to change the viewPage's height to its children's height?

  • I'm using that logic. https://stackoverflow.com/questions/32330639/dynamic-height-viewpager/32410274#32410274 – Emre Akcan Sep 26 '18 at 12:32
  • Well, I think there must be some methods that take too much time in ```onMeasure```. You can use ```TraceView``` to find the method and try to reduce its cost. BTW, ```if (getChildCount() > getCurrentItem())``` the judge seems always to be true? – KevinDsoon Sep 27 '18 at 03:07