Issue
I have a composable button, which can display a text or a loader, depending on state
enum class State { NORMAL, LOADING }
@Composable
fun MyButton(onClick: () -> Unit, text: String, state: State) {
Button(onClick, Modifier.height(60.dp)) {
if (state == State.NORMAL) {
Text(text, fontSize = 32.sp)
} else {
CircularProgressIndicator(color = Color.Yellow)
}
}
}
and I use it like this:
MyButton(
onClick = {
state = if (state == State.NORMAL) State.LOADING else State.NORMAL
},
"hello",
state
)
But the button shrinks when going to loading
state. How can I measure it in normal
state, to assign this measured width in loading
state later?
![](https://i.stack.imgur.com/NxLpk.gif)
Solution
Assuming that the normal state comes before the loading state, you can use the onGloballyPositioned
modifier to get the size of Text
and apply it to the CircularProgressIndicator
.
Something like:
@Composable
fun MyButton(onClick: () -> Unit, text: String, state: State) {
var sizeText by remember { mutableStateOf(IntSize.Zero) }
Button(onClick, Modifier.height(60.dp)) {
if (state == State.NORMAL) {
Text(text, fontSize = 32.sp,
modifier = Modifier.onGloballyPositioned {
sizeText = it.size
})
} else {
Box(Modifier.size(with(LocalDensity.current){ (sizeText.width).toDp()},with(LocalDensity.current){ (sizeText.height).toDp()}),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(color = Color.Yellow)
}
}
}
}
Answered By - Gabriele Mariotti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.