检查ScrollView是否高于屏幕/可滚动

asc*_*sco 14 android android-layout

如何检查a ScrollView是否高于屏幕?当a的内容ScrollView适合屏幕时,ScrollView不可滚动,当它的内容超出屏幕高度时,它可以滚动.我如何检查ScrollView这方面的情况?

Fun*_*onk 23

这是来自ScrollView的代码,它是私有的,但可以适用于在类本身之外使用

/**
 * @return Returns true this ScrollView can be scrolled
 */
private boolean canScroll() {
    View child = getChildAt(0);
    if (child != null) {
        int childHeight = child.getHeight();
        return getHeight() < childHeight + mPaddingTop + mPaddingBottom;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

为时已晚,但是我正在使用以下代码,它对我来说更安全:

if (view.canScrollVertically(1) || view.canScrollVertically(-1)) {
    // you code here
}
Run Code Online (Sandbox Code Playgroud)


Tar*_*ney 5

ScrollView总是有一个孩子.你需要做的就是获得孩子的身高

 int scrollViewHeight = scrollView.getChildAt(0).getHeight();
Run Code Online (Sandbox Code Playgroud)

并计算屏幕的高度

如果两者相等(或scrollView Height更多),那么它适合您的屏幕.

  • 也就是说,如果您的滚动视图覆盖整个屏幕. (4认同)

ole*_*234 5

就我而言,我正在检查创建活动时我的滚动视图(包含文本)是否可以垂直滚动。在手机上,它可以滚动,但在平板电脑上则不能。canScrollVertically返回给我不正确的值,因为它还无法确定。我通过在OnGlobalLayoutListener.

(科特林)

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    // Must use onGlobalLayout or else canScrollVertically will not return the correct value because the layout hasn't been made yet
    scrollView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {

        override fun onGlobalLayout() {
            // If the scrollView can scroll, disable the accept menu item button
            if ( scrollView.canScrollVertically(1) || scrollView.canScrollVertically(-1) )
                acceptMenuItem?.isEnabled = false

            // Remove itself after onGlobalLayout is first called or else it would be called about a million times per second
            scrollView.viewTreeObserver.removeOnGlobalLayoutListener(this)
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

我的用例是显示使用条款。我不希望在用户滚动到底部之前启用接受按钮。我知道这已经晚了,但我希望这能解决一些困惑canScrollVertically