How to check whether ScrollView is scrollable

前端 未结 3 2001
南旧
南旧 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: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
            }
        }
    });
    

提交回复
热议问题