check if an android scrollview can scroll

我是研究僧i 提交于 2020-01-02 00:54:34

问题


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


来源:https://stackoverflow.com/questions/24990992/check-if-an-android-scrollview-can-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!