Here’s an example of using RadioButton in Jetpack Compose to create a group of options with a listener for selection changes.
package com.androindian.check
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
RadioButtonExample()
}
}
}
}
@Composable
fun RadioButtonExample() {
var selectedOption by remember { mutableStateOf("Option 1") }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center
) {
Text(text = "Select an Option:")
Spacer(modifier = Modifier.height(8.dp))
val options = listOf("Option 1", "Option 2", "Option 3")
options.forEach { option ->
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = (option == selectedOption),
onClick = {
selectedOption = option
// Perform action on selection change
println("$option selected!")
}
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = option)
}
Spacer(modifier = Modifier.height(8.dp))
}
Text(text = "Selected: $selectedOption", modifier = Modifier.padding(top = 16.dp))
}
}
Explanation:
- State Management:
var selectedOption by remember { mutableStateOf("Option 1") }
keeps track of the currently selected radio button.
- RadioButton:
selected
: Indicates if the radio button is selected.onClick
: Listener triggered when a radio button is clicked. TheselectedOption
is updated accordingly.
- Dynamic Options:
- The
options
list contains the radio button labels. forEach
creates aRadioButton
and its correspondingText
for each option dynamically.
- The
- UI Update:
- The text
"Selected: $selectedOption"
updates dynamically based on the selected option.
- The text
Output:
- A vertical list of radio buttons labeled “Option 1,” “Option 2,” and “Option 3.”
- When a radio button is selected, the label updates below the group to show the selected option.
You can customize this layout to fit your application’s needs, such as changing the design or adding more complex actions on selection.