在自定义视图组的onLayout方法中调用setLayoutParams()不会有任何作用



我正在扩展RelativeLayout,并希望在onLayout方法中设置我的childViews的位置。这是代码:

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
val margin = Math.round(beautyButton!!.measuredWidth * 1.75).toInt()
beautyButton!!.visibility = View.GONE
var params = defaultSeekbar!!.layoutParams as RelativeLayout.LayoutParams
params.setMargins(margin,0,margin,0)
params.addRule(CENTER_IN_PARENT)
params.removeRule(ALIGN_PARENT_START)
params.removeRule(START_OF)
var params2 = beautySeekbar!!.layoutParams as RelativeLayout.LayoutParams
params2.setMargins(margin,0,margin,0)
params2.addRule(CENTER_IN_PARENT)
params2.removeRule(ALIGN_PARENT_START)
params2.removeRule(START_OF)
super.onLayout(changed, l, t, r, b)
}

我想根据按钮的大小设置搜索栏的位置。而这并没有起到任何作用。我也试过这样的方法,但结果是一样的。

defaultSeekbar!!.layout(margin,defaultSeekbar!!.measuredWidth,margin,defaultSeekbar!!.measuredHeight)

有人能帮我弄清楚如何在将孩子的视图绘制到屏幕上之前设置它们的位置吗?

感谢大家提前给出答案

您缺少一些代码。你不能只检索视图的LayoutParams然后修改它们,因为框架需要某种方式来知道它们已经更新。

添加这些行:

defaultSeekbar!!.layoutParams = params
beautySeekbar!!.layoutParams = params2

请记住,Kotlin喜欢将Java setter/getter方法转换为它所称的属性访问语法,在那里它们看起来像变量。问题是View#setLayoutParams()不仅仅是更改View中的一个变量。它还调用了一些其他东西,以便框架知道View已经更改。

另一件事。我猜您正在执行!!,因为您没有立即初始化SeekBars。如果惰性init语法适用于您的情况,您可以使用它(我不知道,因为您还没有发布该代码(:

defaultSeekbar by lazy { findViewById<WhateverClass>(R.id.whatever) }
beautySeekbar by lazy { findViewById<WhateverClass>(R.id.whatever2) }

它们只有在被调用后才会被初始化,然后该实例将保留。

最新更新