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);
CodePudding user response:
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
}
}
CodePudding user response:
I think this is better since it may have any views other than RadioButton.
val radioButton = radioGroup.children.filter {
it is RadioButton && it.text == "YOUR STRING HERE"
}.map {
it as RadioButton
}.firstOrNull()
radioButton?.let {
it.isChecked = true
}
CodePudding user response:
You can get all the radio buttons inside a radio group by using radioGroup.children
.
And you can iterate over this collection similar to how @rost suggested.
A more functional way of finding the button can be:
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