check if an android scrollview can scroll

2020-08-09 08:46发布

问题:

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?

回答1:

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();


回答2:

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;
}


回答3:

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