我正在扩展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)
}
我想根据Button的大小设置搜索栏的位置。这没有任何作用。我也试过这样的事,但结果是一样的。
defaultSeekbar!!.layout(margin,defaultSeekbar!!.measuredWidth,margin,defaultSeekbar!!.measuredHeight)
有人可以帮助我,弄清楚在将它们绘制到屏幕之前我如何设置我的孩子视图的位置?
提前谢谢大家的答案!
你错过了一些代码。您不能只检索View的LayoutParams然后修改它们,因为框架需要某种方式来知道它们已被更新。
添加以下行:
defaultSeekbar!!.layoutParams = params
beautySeekbar!!.layoutParams = params2
请记住,Kotlin喜欢将Java setter / getter方法转换为它所谓的属性访问语法,它们看起来像变量。问题是View#setLayoutParams()
不只是在View中更改变量。它还调用了其他一些东西,因此框架知道View已被更改。
另一件事。我猜你正在做!!
,因为你没有立即初始化SeekBars。您可以使用lazy init语法,如果它适用于您的情况(我无法分辨,因为您还没有发布该代码):
defaultSeekbar by lazy { findViewById<WhateverClass>(R.id.whatever) }
beautySeekbar by lazy { findViewById<WhateverClass>(R.id.whatever2) }
它们只会在被调用后被初始化,然后该实例将保留。