Android: how to check if a View inside of ScrollView is visible?

后端 未结 14 2101
自闭症患者
自闭症患者 2020-11-22 16:42

I have a ScrollView which holds a series of Views. I would like to be able to determine if a view is currently visible (if any part of it is curre

14条回答
  •  情书的邮戳
    2020-11-22 17:29

    I you want to detect if your View is fully visible, try with this method:

    private boolean isViewVisible(View view) {
        Rect scrollBounds = new Rect();
        mScrollView.getDrawingRect(scrollBounds);
        float top = view.getY();
        float bottom = top + view.getHeight();
        if (scrollBounds.top < top && scrollBounds.bottom > bottom) {
            return true; //View is visible.
        } else {
            return false; //View is NOT visible.
        }
    }
    

    Strictly speaking you can get the visibility of a view with:

    if (myView.getVisibility() == View.VISIBLE) {
        //VISIBLE
    } else {
        //INVISIBLE
    }
    

    The posible constant values of the visibility in a View are:

    VISIBLE This view is visible. Use with setVisibility(int) and android:visibility.

    INVISIBLE This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.

    GONE This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.

提交回复
热议问题