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

时间:2015-12-08 10:20:27

标签: android android-viewpager android-view android-scrollview

我的ScrollView包含两个ViewPagers。热门传呼机的高度始终为48dp。我希望底部寻呼机的高度等于当前页面高度。所以我想我会以编程方式将ViewPager的高度更改为每个页面更改事件的当前页面高度。但是,当我在当前页面视图上调用getHeight()时,它会返回视图可见区域的高度。相反,我想获得一个视图的高度,因为它的父级具有无限高度,即,视图被放置到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) {
        }
    });

1 个答案:

答案 0 :(得分:0)

感谢Hugo Gresse。我最后写了这门课,我对结果感到满意。

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

}