Search code examples
androidkotlinandroid-viewandroid-constraintlayoutandroid-viewtreeobserver

Android kotlin Check if any view slides out of screen when any view changes size


All views in my constraint Layout have layout_height as wrap_content. My first view is bottom to bottom constrained to constraint layout. the next is bottom to top constrained to previous one and so on. My constraint Layout has layout_height as wrap_content too. i want to check if any of my View slides entirely or partially out of screen when any of them dynamically sets text on click.

         fun <T : View> T.afterMeasured( f: T.() -> Unit) {
            viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    if (measuredWidth > 0 && measuredHeight > 0) {
                        println(height)
                    }
                }
            })
        }
        MyConstraintLayout.afterMeasured { }

i tried to use this fun to check constraint layout height every time text is setted in a view and it does but even when any view slides out of screen the height printed is the screen height.

what fun can i use to check if any view slides out of screen when height changes in any view?


Solution

  • Solved by putting afterMeasured on my last view and instead of height getting the Location on screen.

             fun <T : View> T.afterMeasured( f: T.() -> Unit) {
                viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                    override fun onGlobalLayout() {
                        if (measuredWidth > 0 && measuredHeight > 0) {
                            var coordinate= intArrayOf(1,2)
                            getLocationOnScreen(coordinate)
                            println(coordinate[1])
                        }
                    }
                })
            }
    
            wordtxt15.afterMeasured { }
    

    Any better solution is welcome!