0

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.

Tushar Kathuria
  • 645
  • 2
  • 8
  • 22
  • 1
    I would put both Text and Indicator inside a Box, make Text transparent while isLoading and make Indicator invisible while is not loading. – bylazy Jan 24 '22 at 15:55
  • Use the onGloballyPositioned modifier to get the original width – Gabriele Mariotti Jan 24 '22 at 16:23
  • 1
    @GabrieleMariotti, Thanks. I see that you have answered it (https://stackoverflow.com/questions/68227242/how-to-measure-composables) Let me mark this as duplicate – Tushar Kathuria Jan 25 '22 at 06:26

0 Answers0