I have 2 Radio Buttons to change the text color of a text (red text, hardcoded).
But i cant get the Text(color = Color.colorsTextRadio) to work.
I know it says it is a string but who do i get the Red or Green to convert to color.
If i have done something that could be better in thecode please tell because I'm a beginner.
@Composable
fun MainScreen() {
/**
* Text
*/
var text by remember {
mutableStateOf("test")
}
// Event handler
val onTextChange = { value: String ->
text = value
}
/**
* Colors
*/
val colors = listOf("Red", "Green")
var colorsTextRadio by remember {
mutableStateOf(colors[0])
}
// Event Handler
val onTextColorChange = { value: String ->
colorsTextRadio = value
}
Log.d("TAG", "MainScreen: colorsTextRadio $colorsTextRadio")
Column(modifier = Modifier.padding(6.dp)) {
TextField(value = text, onValueChange = onTextChange)
Text(text = text.replace("\n", " "), maxLines = 1, color = Color.Red)
RadioButtonGroup(colors = colors, colorsTextRadio = colorsTextRadio, onClick = onTextColorChange)
}
}
@Composable
fun RadioButtonGroup(
colors: List<String>,
colorsTextRadio: String,
onClick: (String) -> Unit
) {
Column(modifier = Modifier.selectableGroup()) {
colors.forEach { label ->
Row(
modifier = Modifier
.fillMaxWidth()
.height(56.dp)
.selectable(
selected = (colorsTextRadio == label),
onClick = { onClick.invoke(label) },
role = Role.RadioButton
)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
modifier = Modifier.padding(end = 16.dp),
selected = (colorsTextRadio == label),
onClick = null // null recommended for accessibility with screen readers
)
Text(text = label)
}
}
}
}
CodePudding user response:
You can define a data class:
data class ColorLabel(
val label: String,
val color: Color
)
val colors = listOf(
ColorLabel("Red",Red),
ColorLabel("Green", Green))
var colorsTextRadio by remember { mutableStateOf(colors[0].label) }
var colorsText by remember { mutableStateOf(colors[0].color) }
Then apply them to your Composables:
Text(text = text.replace("\n", " "),
maxLines = 1,
color = colorsText)
Column(modifier = Modifier.selectableGroup()) {
colors.forEach { colorlabel->
Row(
modifier = Modifier
.fillMaxWidth()
.height(56.dp)
.selectable(
selected = (colorsTextRadio == colorlabel.label),
onClick = {
colorsTextRadio = colorlabel.label
colorsText = colorlabel.color
},
role = Role.RadioButton
)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
modifier = Modifier.padding(end = 16.dp),
selected = (colorsTextRadio == colorlabel.label),
onClick = null // null recommended for accessibility with screen readers
)
Text(text = colorlabel.label)
}
}
}