androidkotlinandroid-jetpack-compose

Two text button in row center aligned compose


I have been trying to make two text buttons in row with a divider all centrally aligned. I want some like this

enter image description here

For this i have used following code so far

 Box(
            modifier = Modifier.fillMaxWidth(), // Occupy full width
            contentAlignment = Alignment.Center // Center content horizontally
        ) {
            Row(
                modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min),
                horizontalArrangement = Arrangement.Center, // Center items horizontally
                verticalAlignment = Alignment.CenterVertically // Center vertically (optional)
            ) {
                TextButton(onClick = { /* Action for Button 1 */ }) {
                    Text(modifier = Modifier, text = "Button 1")
                }

                Divider(
                    color = Color.Gray,
                    modifier = Modifier
                        .fillMaxHeight()
                        .width(1.dp)
                )

                TextButton(onClick = { /* Action for Button 2 */ }) {
                    Text("Button 2")
                }
            }
        }

But not able to make the buttons centrally aligned. This is my result

enter image description here

Any one can help me out !


Solution

  • In your Row instead of Arrangement.Center, use Arrangement.SpaceEvenly:

    Place children such that they are spaced evenly across the main axis, including free space before the first child and after the last child. Visually: #1#2#3# for LTR and #3#2#1# for RTL.

    Row(
        modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min),
        horizontalArrangement = Arrangement.SpaceEvenly,
        verticalAlignment = Alignment.CenterVertically 
    ) {
        ...
    }
    

    This will make the buttons clickable only in the area their content is rendered in. In order to make their clikable area as large as possible, use the weight(1f) modifier:

    Row(
        modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min),
        verticalAlignment = Alignment.CenterVertically
    ) {
        TextButton(
            onClick = { /* Action for Button 1 */ },
            modifier = Modifier.weight(1f)
        ) {
            Text(modifier = Modifier, text = "Button 1")
        }
    
        Divider(
            color = Color.Gray,
            modifier = Modifier
                .fillMaxHeight()
                .width(1.dp)
        )
    
        TextButton(
            onClick = { /* Action for Button 2 */ },
            modifier = Modifier.weight(1f)
        ) {
            Text("Button 2")
        }
    }