通过 String 的值设置 RadioGroup 选中的 RadioButton

Set RadioGroup selected RadioButton by value of String

由于 Kotlin 不支持传统的 for 循环,如果字符串 x 值与 RadioButton 文本匹配,是否有办法 select RadioGroup 中的 RadioButton?

像这样的东西可以在 Java 上工作,但不能在 Kotlin 上工作

 for(i...radioGroup.childCount){
        int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
        View radioButton = radioButtonGroup.findViewById(radioButtonID);
        int idx = radioButtonGroup.indexOfChild(radioButton);
    }

然后像这样的代码 select 基于字符串值

的正确收音机
if(radioBtn.text.toString.equals("Sample"))
       radioBt.check(R.id.radio1);
    else 
       radioBt.check(R.id.radio2);

rg - 您的广播组

for (rbPosition in 0 until rg.childCount) {
            val rb = rg.getChildAt(rbPosition) as RadioButton
            if (rb.text == yourText) {
                //do stuff for example rb.isChecked = true
            }
        }

您可以使用radioGroup.children获取单选组内的所有单选按钮。
您可以像@rost 建议的那样迭代这个集合。
查找按钮的更实用的方法可以是:

val radioButton = radioGroup.children
                      .map { it as RadioButton } // Convert the sequence of Views to sequence of RadioButtons
                      .find { it.text == buttonText }!! // Don't use this !! if there's a possibility that no RadioButton with provided text exists

// Now you have the button, use it however you want

我认为这更好,因为它可能有 RadioButton 以外的任何视图。

val radioButton = radioGroup.children.filter {
        it is RadioButton && it.text == "YOUR STRING HERE"
    }.map {
        it as RadioButton
    }.firstOrNull()
    
radioButton?.let { 
        it.isChecked = true
    }