Android:ScrollView的总高度

Eri*_*rik 37 android scroll scrollview

我有一个自定义ScrollView(扩展android.widget.ScrollView),我在我的布局中使用.我想测量此scrollview内容的总高度.getHeight()和getMeasuredHeight()不会给我正确的值(数字太高).

背景信息:我想确定用户滚动了多远.我使用onScrollChanged来获取X值,但我需要知道一个百分比,所以我需要总滚动条高度.

非常感谢!埃里克

sat*_*ine 94

ScrollView总是有一个孩子.您需要做的就是获得孩子的身高以确定总身高:

int totalHeight = scrollView.getChildAt(0).getHeight();
Run Code Online (Sandbox Code Playgroud)

  • 您是否曾在onCreate或测量之前询问它的高度?稍后尝试获得高度,请看这个问题:http://stackoverflow.com/questions/7733813/how-can-you-tell-when-a-layout-has-been-drawn (3认同)
  • 如果你想知道它会滚动多少,你可以使用它自己的高度和它的子高度之间的差异:`scrollView.getChildAt(0).getHeight() - scrollView.getHeight()` (3认同)

Nin*_*off 6

查看ScrollView的源码。不幸的是,此方法是私有的,但您可以将其复制到您自己的代码中。请注意,其他答案不考虑填充

private int getScrollRange() {
    int scrollRange = 0;
    if (getChildCount() > 0) {
        View child = getChildAt(0);
        scrollRange = Math.max(0,
                child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop));
    }
    return scrollRange;
}
Run Code Online (Sandbox Code Playgroud)

  • 对于那些想要使用此代码的人,以下将起作用:`Math.max(0, child.getHeight() - (scrollView.getHeight() - scrollView.getPaddingBottom() - scrollView.getPaddingTop()));` (4认同)