Scrollview:检查视图在屏幕上是否可见

问题描述 投票:0回答:4

我有一个 ScrollView 定义如下:

<ScrollView
    ... 
    .../>
    <LinearLayout
        ...
        ...>

        <!-- content -->

    </LinearLayout>
</ScrollView>

我用一些 ImageView 动态填充 LinearLayout。现在,有没有办法检查 ImageView 何时变得可见或不可见(例如当我向下滚动时)?

android android-scrollview
4个回答
32
投票

要检查视图是否完全/部分可见,您可以使用:

boolean isViewVisible = view.isShown();

要确定它是否完全可见,请使用以下方法:

Rect rect = new Rect();
if(view.getGlobalVisibleRect(rect) 
    && view.getHeight() == rect.height() 
    && view.getWidth() == rect.width() ) {
    // view is fully visible on screen
}

11
投票

我会转发给你这个答案

如果图像是布局的一部分,它可能是“View.VISIBLE”,但这并不意味着它在可见屏幕的范围内。如果这就是你所追求的;这会起作用:

Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
    // imageView is within the visible window
} else {
    // imageView is not within the visible window
}

3
投票

我花了很多功夫才得到准确的答案,以下解决了我的问题

final ScrollView scrollView = findViewById(R.id.scrollView);

scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                Rect scrollBounds = new Rect();
                scrollView.getHitRect(scrollBounds);
                if (yourImageView.getLocalVisibleRect(scrollBounds)) {
                    // The ImageView is Visible on the screen while scrolling
                } else {
                    // The ImageView is not Visible on the screen while scrolling
            }
            }
        });

OnScrollChangedListener 中的代码不断检查 Imageview 是否可见并显示在屏幕上,一旦滚动并且 imageview 不可见,它就会立即被检测到


0
投票

我为此编写了 Kotlin 扩展函数:

fun View.isViewFullyVisible(): Boolean {
    val localVisibleRect = Rect()
    getLocalVisibleRect(localVisibleRect)
    return localVisibleRect.top == 0 && localVisibleRect.bottom == height
}
© www.soinside.com 2019 - 2024. All rights reserved.