I'm building a segmented control in Jetpack Compose using a Row with Button composables to create a visual toggle. While the button size is working as expected, the text within the buttons is not displaying properly. Here's my SegmentedControl composable:
@OptIn(ExperimentalMaterial3Api::class, androidx.compose.ui.tooling.preview.Preview::class)
@Composable
fun SegmentedControl(
items: List<String>,
selectedItemIndex: Int,
onSelectedItemChange: (Int) -> Unit,
modifier: Modifier = Modifier // Added this modifier parameter
) {
Row(
modifier = modifier.fillMaxWidth(), // Fill width with applied modifier
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
items.forEachIndexed { index, label ->
Button(
onClick = { onSelectedItemChange(index) },
shape = if (index == selectedItemIndex) {
RoundedCornerShape(8.dp)
} else {
CircleShape
},
colors = ButtonDefaults.buttonColors(
containerColor = if (index == selectedItemIndex) Color.LightGray else Color.White,
contentColor = if (index == selectedItemIndex) Color.Black else Color.Black
),
modifier = Modifier
.padding(4.dp)
.weight(1f)
) {
// Apply weight to a Row inside the Button
Row(
modifier = Modifier
.fillMaxWidth()
.weight(1f), // Apply weight to the Row
horizontalArrangement = Arrangement.Start // Align text to the start of the row
) {
Text(
text = label,
fontFamily = helveticaNormal,
fontSize = 10.sp,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
)
}
}
}
}
}
The buttons are the correct size, but the text inside them is either not visible or not aligned properly.
I've tried adjusting the padding and fontSize of the Text composable. I've experimented with different horizontalArrangement values within the inner Row.
I am assuming that you want to align the text to the left inside of the Button
.
The content of the Button by default has a RowScope
, so you don't need an extra Row
inside of the Button
. You can apply the weight
Modifier directly onto the Text
to make it fill the button width. Then, specify the textAlign
attribute and set it to TextAlign.Start
.
Please update your code like this:
Button(
//...
) {
Text(
text = label,
textAlign = TextAlign.Start, // set text alignment here
fontSize = 10.sp,
modifier = Modifier.weight(1f) // add weight here, remove padding
)
}
Output: