How to retain button width on content change in jetpack compose

278 views Asked by At

I am trying to implement a generic button component that has a loading state. I came up with following approach that works great:

@Preview
@Composable
private fun CustomButtonPreview() {
    var isLoading by remember { mutableStateOf(false) }
    CustomButton(
        text = "Some action",
        isLoading = isLoading,
        onClick = { isLoading = !isLoading }
    )
}

@Composable
private fun CustomButton(
    text: String,
    isLoading: Boolean = false,
    onClick: () -> Unit = {}
) {
    Button(onClick = onClick) {
        if(isLoading) {
            CircularProgressIndicator(
                modifier = Modifier.size(18.dp),
                color = White,
                strokeWidth = 2.dp
            )
        } else {
            Text(text)
        }
    }
}

With this approach, width of the button is reduced when it enters the loading state. How can we retain the original button width when moving to the loading state? I don't want to take width as parameter because I want the button to be automatically sized as per the original content.

0

There are 0 answers