15

I am trying to put a ViewPager with different fragments with different heights. I know that wrap_content is not working with ViewPager so I am trying to set pager height dinamically. I am setting the pager height in a page listener:

...
        indicator.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int selected) {
                final View view = fragments[selected].getView();
                if (view != null) {
                    pager.setLayoutParams(new LayoutParams(
                            LayoutParams.MATCH_PARENT, view
                                    .getMeasuredHeight()));

                }

            }

Unfortunately it is not working because the value returned by getMeasuredHeight() on Fragment is wrong. What am I doing wrong?

Matroska
  • 6,885
  • 14
  • 63
  • 99

2 Answers2

18

This is my solution:

    ViewTreeObserver viewTreeObserver = mViewPager.getViewTreeObserver();
    viewTreeObserver
            .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {

                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT);

                    int viewPagerWidth = mViewPager.getWidth();
                    float viewPagerHeight = (float) (viewPagerWidth * FEATURED_IMAGE_RATIO);

                    layoutParams.width = viewPagerWidth;
                    layoutParams.height = (int) viewPagerHeight;

                    mViewPager.setLayoutParams(layoutParams);
                    mViewPager.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
            });

I call it in onResume();

czaku
  • 829
  • 9
  • 20
1

Try to set its parameters in onLayout() of the viewpager

Ercan
  • 3,705
  • 1
  • 22
  • 37
  • so are you suggesting to extend the viewPager? The problem is that the pager should have the height of the displayed fragment, so I don't understand how this could be solved in onLayout(). – Matroska Nov 16 '12 at 15:31