How to check whether ScrollView is scrollable

前端 未结 3 2000
南旧
南旧 2020-12-17 19:14

I was wondering, how to check whether the current ScrollView is scrollable? It seems that, there isn\'t public method called canScroll or isS

相关标签:
3条回答
  • 2020-12-17 19:29
    scrollView.viewTreeObserver
            .addOnGlobalLayoutListener {
    
                val isScrollable = scrollView.canScrollVertically(1)
            }
    
    0 讨论(0)
  • 2020-12-17 19:30

    You can do some little math to calculate the views raw height and the height of the content. If the difference of this heights is < 0 the view is scrollable.

    To calculate the raw height you can use View.getMeasuredHeight(). Because ScrollView is a ViewGroup and has max one child, get the height of that child with ViewGroup.getChildAt(0).getHeight();

    Use a ViewTreeObserver to get the heights, because it will be called at the moment the layout / view is changing the visibility, otherwise the heights could be 0.

    ScrollView scrollView = (ScrollView)findViewById(R.id...);
    ViewTreeObserver observer = scrollView.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int viewHeight = scrollView.getMeasuredHeight();
            int contentHeight = scrollView.getChildAt(0).getHeight();
            if(viewHeight - contentHeight < 0) {
                // scrollable
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-17 19:32

    I think I might be missing something, but shouldn't it be as simple as checking if

    scrollView.getHeight() >= parentView.getMeasuredHeight()
    

    you might actually need: scrollView.getChildAt(0).getHeight() and/or parentView.getHeight() instead, but the idea is the same.

    0 讨论(0)
提交回复
热议问题