Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

Jetpack Compose tilted row with buttons


I'm developing an Android app in Jetpack Compose, which is basically a big form. I wanted to add a little style to it with custom buttons, but I don't really know how to make them.

What I'm trying to achieve:

Example button style

In that layout there will be 2 Buttons with a TextField in the middle. How can I tilt them so it looks like the image?


Solution

  • You can build a custom shape like this:

    class ParallelogramShape(private val angle: Float): Shape {
        override fun createOutline(
            size: Size,
            layoutDirection: LayoutDirection,
            density: Density,
        ) = Outline.Generic(
            Path().apply {
                val width = size.width - size.height / tan(angle)
                moveTo(size.width - width, 0f)
                lineTo(size.width, 0f)
                lineTo(width, size.height)
                lineTo(0f, size.height)
                lineTo(size.width - width, 0f)
            }
        )
    }
    

    And use it like this:

    val border = BorderStroke(1.dp, Color.Black)
    val shape = ParallelogramShape(45f)
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .padding(10.dp)
            .border(border, shape = shape)
    ) {
        var counter by remember { mutableStateOf(10) }
        TextButton(
            onClick = { counter -= 1 },
            shape = shape,
            border = border,
            modifier = Modifier
                .height(45.dp)
                .width(100.dp)
        ) {
            Text("-")
        }
        Text(counter.toString())
        TextButton(
            onClick = { counter += 1 },
            shape = shape,
            border = border,
            modifier = Modifier
                .height(45.dp)
                .width(100.dp)
        ) {
            Text("+")
        }
    }
    

    Result: