检查android scrollview是否可以滚动

joh*_*nvs 17 android scrollview

你知道是否有可能知道Android Widget ScrollView是否可以滚动?如果它有足够的空间,则不需要滚动,但只要维度超过最大值,窗口小部件就可以滚动.

我在参考文献中没有看到可以提供此信息的方法.也许有可能在scrollview中使用linearlayout的大小做一些事情?

joh*_*nvs 16

我使用以下代码灵感来自/sf/answers/1300202991/,它的工作原理!

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

  • 附加注释:它在创建和显示视图时起作用。不能在 onCreate 中使用(例如:getHeight 将返回 0,对于 match_parent) (2认同)

小智 16

感谢:@johanvs和 /sf/answers/1300202991/

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;
}
Run Code Online (Sandbox Code Playgroud)


Nes*_*rez 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
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)