考虑到其父级具有无限高度,如何获得视图高度?

How to get view height considering its parent has infinite height?

我有一个包含两个 ViewPagers 的 ScrollView。 Top pager 的高度始终为 48dp。我希望底部寻呼机的高度等于当前页面高度。所以我想我会在每次页面更改事件中以编程方式将 ViewPager 的高度更改为当前页面高度。但是,当我在当前页面视图上调用 getHeight() 时,它是视图可见区域的 returns 高度。相反,考虑到其父级具有无限高度,我想获得视图的高度,即,就像将视图放在 ScrollView 而不是 ViewPager 中一样。可以测量这个吗?

XML:

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <android.support.v4.view.ViewPager
            android:id="@+id/top_pager"
            android:layout_width="match_parent"
            android:layout_height="48dp" >
        </android.support.v4.view.ViewPager>

        <android.support.v4.view.ViewPager
            android:id="@+id/bottom_pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </android.support.v4.view.ViewPager>
    </LinearLayout>
</ScrollView>

JAVA:

bottomPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            Object pageTag = bottomPager.getTag();
            View currentPageView = bottomPager.findViewWithTag(pageTag);

            int height = currentPageView.getHeight();
            // height above is always smaller than the screen height
            // no matter how much content currentPage has.
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });

谢谢雨果·格雷斯。我最终写了这个 class,我对结果很满意。

/**
 * This ViewPager continuously adjusts its height to the height of the current
 * page. This class works assuming that each page view has tag that is equal to
 * page position in the adapter. Hence, make sure to set page tags when using
 * this class.
 */
public class HeightAdjustingViewPager extends ViewPager {

    public HeightAdjustingViewPager(Context context) {
        super(context);
    }

    public HeightAdjustingViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        for (int i = 0; i < getChildCount(); i++) {
            View pageView = getChildAt(i);
            pageView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int pageHeight = pageView.getMeasuredHeight();

            Object pageTag = pageView.getTag();
            if (pageTag.equals(getCurrentItem())) {
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(pageHeight, MeasureSpec.EXACTLY);
            }
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}