本文介绍了动态设置ViewPager高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图把 ViewPager 与不同高度不同的片段。我知道, WRAP_CONTENT 不工作与 ViewPager 所以我想dinamically设置寻呼机的高度。我设置的寻呼机高度在页面监听器:

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

                }

            }

不幸的是它不工作,因为通过 getMeasuredHeight()片段返回的值是错误的。我究竟做错了什么?

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

推荐答案

这是我的解决方案:

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

I call it in onResume();

这篇关于动态设置ViewPager高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:38