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

后端 未结 14 2034
自闭症患者
自闭症患者 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:40

    This extension help detect view fully visible.
    It also work if your View is a child of child of ... of ScrollView (eg: ScrollView -> LinearLayout -> ContraintLayout -> ... -> YourView).

    fun ScrollView.isViewVisible(view: View): Boolean {
        val scrollBounds = Rect()
        this.getDrawingRect(scrollBounds)
        var top = 0f
        var temp = view
        while (temp !is ScrollView){
            top += (temp).y
            temp = temp.parent as View
        }
        val bottom = top + view.height
        return scrollBounds.top < top && scrollBounds.bottom > bottom
    }
    

    Note

    1) view.getY() and view.getX() return the x,y value to FIRST PARENT.

    2) Here is example about how getDrawingRect will return Link

提交回复
热议问题