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

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

    Kotlin way;

    An extension for listing scroll view's scroll and get an action if child view visible on screen.

    @SuppressLint("ClickableViewAccessibility")
    fun View.setChildViewOnScreenListener(view: View, action: () -> Unit) {
        val visibleScreen = Rect()
    
        this.setOnTouchListener { _, motionEvent ->
            if (motionEvent.action == MotionEvent.ACTION_MOVE) {
                this.getDrawingRect(visibleScreen)
    
                if (view.getLocalVisibleRect(visibleScreen)) {
                    action()
                }
            }
    
            false
        }
    }
    

    Use this extension function for any scrollable view

    nestedScrollView.setChildViewOnScreenListener(childView) {
                   action()
                }
    

提交回复
热议问题