【问题标题】:Android checking radio button in code makes it stay checked in a radiogroupAndroid 检查代码中的单选按钮使其在单选组中保持选中状态
【发布时间】:2018-10-31 22:39:56
【问题描述】:

我在RadioGroup 中有一个动态添加的单选按钮。而且我必须根据一些数据在代码中检查其中一个。

现在,问题是在显示单选按钮并且用户检查同一组中的另一个单选按钮后,之前选择的单选按钮仍处于选中状态...导致两个选中的RadioButtons

这就是我在 Kotlin 中渲染按钮的方式:

val rg = RadioGroup(this).apply { orientation = RadioGroup.HORIZONTAL }
choices.values.forEach { c ->
    rg.addView(RadioButton(this).apply {
        tag = someTag
        text = c
        isChecked = answer.equals(c) // condition
    })
}

奇怪的是,如果没有以编程方式检查 RadioButton,一切正常。

【问题讨论】:

  • 你在使用 kotlin-kapt 插件吗? (只是为了让我知道在我的答案中使用什么)
  • @AnthonyCannon 没有。只是普通的 kotlin。

标签: android kotlin radio-button


【解决方案1】:

而不是设置radioButton.isChecked = ...。尝试使用radioGroup.check(id)

【讨论】:

  • 谢谢伙计。 radioGroup.check 调用中的 index 是单选按钮 Id。除此之外,我必须在添加所有单选按钮后拨打radioGroup.check(index)
  • 啊,是的,我的错。生病更新我的答案。很高兴我能提供帮助。
  • 我的错,我在做 radioButton.isSelected = ... 它是 isChecked 而不是
【解决方案2】:

我将此代码用于 RadioButton。

radio_rg.setOnCheckedChangeListener { _, checkedId ->
    val radio: RadioButton = findViewById(checkedId)
    when (radio) {
        radioBtn1 -> {
            // some code
        }
        radioBtn2 -> {
             // some code
        }
    }
}

希望对你有所帮助。

关于没有选中 RadioButton,我从未尝试过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2017-12-22
    相关资源
    最近更新 更多