42

I have a custom ScrollView (extended android.widget.ScrollView) which I use in my layout. I want to measure the total height of the contents of this scrollview. getHeight() and getMeasuredHeight() don't give me correct values (too high numbers).

Background information: I want to determine how far the user has scrolled. I use onScrollChanged to get the X value, but I need to know a percentage so I'll need the total scrollbar height.

Thanks a lot! Erik

Erik
  • 5,681
  • 8
  • 31
  • 32
  • Take a look at http://stackoverflow.com/questions/3513594/android-scrollview-setonscrolllistener-like-listview for a hint – Mikpa Nov 22 '10 at 12:49

2 Answers2

115

A ScrollView always has 1 child. All you need to do is get the height of the child to determine the total height:

int totalHeight = scrollView.getChildAt(0).getHeight();
satur9nine
  • 13,927
  • 5
  • 80
  • 123
  • 1
    My child view returns 0 even though it scrolls. – Ragunath Jawahar Sep 01 '12 at 17:51
  • 4
    Did you ask for it's height in onCreate or before it has been measured? Try getting the height later, see this question: http://stackoverflow.com/questions/7733813/how-can-you-tell-when-a-layout-has-been-drawn – satur9nine Sep 01 '12 at 20:02
  • 1
    Only way to be sure child view measurements are calculated is ViewTreeObserver.OnGlobalLayoutListener. Be sure that this will receive callback for each view registered to ViewTreeObserver and you need to distinguish between them. Here is the link: http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html – Gökhan Barış Aker May 21 '14 at 11:37
  • 4
    And if you want to know how much it will scroll, you can use the difference between its own height and its child's height: `scrollView.getChildAt(0).getHeight() - scrollView.getHeight()` – karl Nov 30 '16 at 17:36
7

See the source of ScrollView. Unfortunately, this method is private, but you could copy it into your own code. Note that other answers don't take padding into account

private int getScrollRange() {
    int scrollRange = 0;
    if (getChildCount() > 0) {
        View child = getChildAt(0);
        scrollRange = Math.max(0,
                child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop));
    }
    return scrollRange;
}
Nino van Hooff
  • 3,677
  • 1
  • 36
  • 52
  • 4
    For those who want to use this code, the following will work: `Math.max(0, child.getHeight() - (scrollView.getHeight() - scrollView.getPaddingBottom() - scrollView.getPaddingTop()));` – rjr-apps Apr 18 '18 at 16:11