动态设置 ViewPager 高度

Dynamically set ViewPager height(动态设置 ViewPager 高度)

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

问题描述

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

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()Fragment 上返回的值是错误的.我做错了什么?

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 高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:动态设置 ViewPager 高度

基础教程推荐