我如何在 Anko DSL (Android) 中设置单选按钮的 layout_weight 值?

How can I set value of layout_weight of a radio button in Anko DSL (Android)?

我使用 Anko DSL 创建 UI 而不是 XML。但是当我要以 Anko 方式设置单选按钮的 layout_weight 参数时,我遇到了错误。

我试过以下方式:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    verticalLayout() {
        radioGroup() {
            orientation = LinearLayout.HORIZONTAL
            radioButton {
                id = RADIO_SECOND
                text = "second(s)"

            }.lparams(width = wrapContent, height = wrapContent, weight = 0.25F)

            // Few more radio button
        }
    }
}

但是报错Error:(107, 19) 'inline fun <T : View> RadioButton.lparams(width: Int = ..., height: Int = ..., weight: Float): RadioButton' can't be called in this context by implicit receiver. Use the explicit one if necessary

我该如何继续?

通过指定 radioButtonweight 参数,您选择使用 Anko 的 _LinearLayout class 上定义的 lparams 函数,所以您基本上是在 verticalLayout 的上下文中尝试给 radioButton 一个权重,您已经包装了整个布局。

要在 radioGroup 的上下文中赋予它权重,您可以使用另一个 lparams 函数,其类似参数名为 initWeight:

verticalLayout {
    radioGroup {
        orientation = LinearLayout.HORIZONTAL
        radioButton {
            id = RADIO_SECOND
            text = "second(s)"
        }.lparams(width = wrapContent, height = wrapContent, initWeight = 0.25F)
    }
}

这会将调用置于正确的上下文中。