Search code examples
androidkotlinandroid-radiobuttonandroid-radiogroup

Set RadioGroup selected RadioButton by value of String


Since Kotlin does not support traditional for loop is there a way to select a RadioButton in a RadioGroup if the String x value matched the RadioButton text?

Something like this will work on Java but not in Kotlin

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

Then something like this code to select the correct radio based on String value

if(radioBtn.text.toString.equals("Sample"))
       radioBt.check(R.id.radio1);
    else 
       radioBt.check(R.id.radio2);

Solution

  • rg - your radioGroup

    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
                }
            }