ViewCompat.setOnApplyWindowInsetsListener not dispatching on MotionLayout I need to get the system toolbar height

20 views Asked by At

I have a layout that is wrapped in a MotionLayout. I use a Guideline at the top of the layout to set an offset at the top of the screen so when the user drags the layout up the view does not scroll under the status bar. I have been trying different approaches to get this offset value. The correct way to do this is to use something like this.

binding.root.viewTreeObserver.addOnGlobalLayoutListener(
        object : ViewTreeObserver.OnGlobalLayoutListener {
            /**
             * Callback method to be invoked when the global layout state or the visibility of views
             * within the view tree changes
             */
            override fun onGlobalLayout() {
            
                ViewCompat.setOnApplyWindowInsetsListener(binding.container)
                {
                        view, insets ->


                    val statusBarHeight = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        // For Android Q and above, directly use systemWindowInsetTop
                        insets.systemWindowInsetTop
                    } else {
                        // For below Android Q, use WindowInsetsCompat
                        insets.getInsets(WindowInsetsCompat.Type.statusBars()).top
                    }


                    view.setPadding(
                        view.paddingLeft, // keep left padding unchanged
                        statusBarHeight, // add status bar height to the top padding
                        view.paddingRight, // keep right padding unchanged
                        view.paddingBottom // keep bottom padding unchanged
                    )
              
                    x.setGuidelineBegin(
                        statusBarHeight
                    )
                    // Return the insets so other views can also use them
                    WindowInsetsCompat.CONSUMED
                }
                binding.root.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })

However the code never dispatches. The onGlobalLayout runs; and I have tried attaching it in the onStart so I know that the layout hasn't happened yet; and also tried running it multiple callbacks without the GlobalLayoutListener.

Is there any solution to this issue?

0

There are 0 answers