27

Do you know if it is possible to know if an Android Widget ScrollView can scroll? If it has enough space it doesn't need to scroll, but as soon as a dimension exceeds a maximum value the widget can scroll.

I don't see in the reference a method who can give this information. Maybe is it possible to do something with the size of the linearlayout inside the scrollview?

johanvs
  • 4,273
  • 3
  • 24
  • 26

3 Answers3

35

I used the following code inspired by https://stackoverflow.com/a/18574328/3439686 and it works!

ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
int childHeight = ((LinearLayout)findViewById(R.id.scrollContent)).getHeight();
boolean isScrollable = scrollView.getHeight() < childHeight + scrollView.getPaddingTop() + scrollView.getPaddingBottom();
Community
  • 1
  • 1
johanvs
  • 4,273
  • 3
  • 24
  • 26
  • 3
    additional comment: it works when view created and displayed. it's not possible to use in onCreate (for ex: getHeight will return 0, for match_parent) – Siarhei Jul 16 '16 at 09:16
  • The answer is correct, but the method should be called after view created. Check out here: http://stackoverflow.com/questions/19503573/how-to-check-whether-scrollview-is-scrollable – thanhbinh84 Jan 05 '17 at 02:07
28

Thanks to: @johanvs and https://stackoverflow.com/a/18574328/3439686

private boolean canScroll(HorizontalScrollView horizontalScrollView) {
    View child = (View) horizontalScrollView.getChildAt(0);
    if (child != null) {
        int childWidth = (child).getWidth();
        return horizontalScrollView.getWidth() < childWidth + horizontalScrollView.getPaddingLeft() + horizontalScrollView.getPaddingRight();
    }
    return false;

}

private boolean canScroll(ScrollView scrollView) {
    View child = (View) scrollView.getChildAt(0);
    if (child != null) {
        int childHeight = (child).getHeight();
        return scrollView.getHeight() < childHeight + scrollView.getPaddingTop() + scrollView.getPaddingBottom();
    }
    return false;
}
Community
  • 1
  • 1
Fawad Badar
  • 436
  • 5
  • 7
5

In addition to @johanvs response:

You should wait for view beign displayed

 final ScrollView scrollView = (ScrollView) v.findViewById(R.id.scrollView);
    ViewTreeObserver viewTreeObserver = scrollView.getViewTreeObserver();

    viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            int childHeight = ((LinearLayout) v.findViewById(R.id.dataContent)).getHeight();
            boolean isScrollable = scrollView.getHeight() < childHeight + scrollView.getPaddingTop() + scrollView.getPaddingBottom();
            if (isScrollable) {
                //Urrah! is scrollable
            }
        }
    });
Nestor Perez
  • 827
  • 11
  • 17