Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set ViewPager height

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?

like image 646
Matroska Avatar asked Nov 16 '12 15:11

Matroska


1 Answers

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();

like image 135
czaku Avatar answered Sep 27 '22 21:09

czaku