检查 Android ScrollView 是否可以滚动。

27

您知道如何确定Android Widget ScrollView是否可以滚动吗? 如果有足够的空间,它就不需要滚动,但是一旦一个尺寸超过最大值,小部件就可以滚动。

我在参考文献中没有看到可以提供此信息的方法。 也许可以通过ScrollView内LinearLayout的大小来实现什么操作?


请查看https://dev59.com/KWMl5IYBdhLWcg3wOU5g#18574328,它应该会对你有所帮助。 - G.T.
https://dev59.com/Om855IYBdhLWcg3wlFWP - Shailendra Madda
@G.T. 谢谢!它回答了我的问题。 - johanvs
3个回答

35

我使用了受到https://dev59.com/KWMl5IYBdhLWcg3wOU5g#18574328启发的以下代码,并且它能正常工作!

ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
int childHeight = ((LinearLayout)findViewById(R.id.scrollContent)).getHeight();
boolean isScrollable = scrollView.getHeight() < childHeight + scrollView.getPaddingTop() + scrollView.getPaddingBottom();

3
附加评论:它只在视图创建和显示时起作用。无法在onCreate中使用(例如:getHeight将返回0,对于match_parent) - Siarhei
答案是正确的,但方法应该在视图创建后调用。请查看此处:https://dev59.com/fWIk5IYBdhLWcg3wMLiI - thanhbinh84

28

感谢:@johanvs 和 https://dev59.com/KWMl5IYBdhLWcg3wOU5g#18574328

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

5
除了@johanvs的回答之外:
您应该等待视图显示。
 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
            }
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接