To find the text of a selected radio button in Kotlin for Android, you can follow these steps:
- Declare a reference to the radio group in your activity or fragment. For example, if your radio group has an ID of
radioGroup
, you can declare it as follows:
val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
2.Set a listener on the radio group to detect when a radio button is selected. You can use the setOnCheckedChangeListener method to achieve this:
radioGroup.setOnCheckedChangeListener { group, checkedId ->
val selectedRadioButton = findViewById<RadioButton>(checkedId)
val selectedText = selectedRadioButton.text.toString()
// Use the selectedText as needed
}
- Inside the listener, retrieve the selected radio button using the provided
checkedId
parameter. Then, you can access the text of the selected radio button using the text property, and convert it to a string using .toString()
The selectedText variable will contain the text of the selected radio button, which you can use as needed in your application.
Remember to replace R.id.radioGroup
with the actual ID
of your radio group in your layout file.