15

我正在尝试放置ViewPager具有不同高度的不同片段。我知道这wrap_content不起作用,ViewPager所以我试图动态设置寻呼机高度。我在页面侦听器中设置寻呼机高度:

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

                }

            }

不幸的是,它不起作用,因为getMeasuredHeight()on返回的值Fragment是错误的。我究竟做错了什么?

4

2 回答 2

19

这是我的解决方案:

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

我在 onResume(); 中调用它

于 2013-10-21T22:12:55.290 回答
1

尝试在 viewpager 的 onLayout() 中设置它的参数

于 2012-11-16T15:21:40.713 回答