安卓Kotlin 设置控件宽高比

使用该控件的OnGlobalLayoutListener即可获得其宽/高,并进行重新绘制

private fun setWHRatio(v: View){
    
    
    v.viewTreeObserver.addOnGlobalLayoutListener(object :ViewTreeObserver.OnGlobalLayoutListener{
    
    
        override fun onGlobalLayout() {
    
    
            Log.d("MyRatio", "Width: ${
      
      v.width}")
            v.layoutParams.height = (v.width * 1.5).toInt() //可自行设置比例
            v.invalidate()
            v.viewTreeObserver.removeOnGlobalLayoutListener(this)
        }
    })
}

使用时,只需要在onCreate中调用该函数即可

setWHRatio(myView)

猜你喜欢

转载自blog.csdn.net/u011570312/article/details/107729032