get layout height and width at run time android

前端 未结 6 1256
死守一世寂寞
死守一世寂寞 2020-11-29 05:50

How can I get width and height of a linear layout which is defined in xml as fill_parent both in height and width? I have tried onmeasure method but I dont know why it is no

6条回答
  •  执笔经年
    2020-11-29 06:42

    A generic approach using Kotlin based on MGDroid's answer for API 16+.

    /**
     * Align height of a container from wrap-content to actual height at runtime.
     * */
    private fun  alignContainerHeight(container: T) {
        container.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
    
                // Obtain runtime height
                val availableHeight = container.measuredHeight
    
                if (availableHeight > 0) {
                    container.viewTreeObserver.removeOnGlobalLayoutListener(this)
                    setContainerHeight(container, availableHeight)
                }
            }
        })
    }
    
    /**
     * Note: Assumes that the parent is a LinearLayout.
     * */
    private fun  setContainerHeight(container: T, availableHeight: Int) {
        val availableWidth = container.measuredWidth
        val params = LinearLayout.LayoutParams(availableWidth, availableHeight)
    
        // Note: getLayoutParams() returns null if no parent exists
        if (container.layoutParams != null) {
            container.layoutParams = params
        }
    }
    

提交回复
热议问题