Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...