25

Older versions of Jetpack compose dev-0.x used to have a Center composable to center a widget.

However, in the alpha version it has been removed and no specific composable made to handle this task.

In my case I want to show a progress indicator at the center until data is fetched:

Surface(color = MaterialTheme.colors.background) {
    val state = viewModel.userState
    if (state == null) {
        CircularProgressIndicator()
    } else {
        UserDigest(state = state)
    }
}

The result is obviously something like this:

enter image description here

And the indicator is at the corner.


Adding fillMaxSize() to the Indicator does not help either:

CircularProgressIndicator(modifier = Modifier.fillMaxSize())

enter image description here

So, how do I move it (generally a composable) to the center of an area?

2 Answers 2

54

You have to use a parent container.
For example:

Box(
   contentAlignment = Alignment.Center,
   modifier = Modifier.fillMaxSize() 
) {
    CircularProgressIndicator()
}

or:

Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
) {
    CircularProgressIndicator()
}

enter image description here

2
  • 2
    In compose 1.0.0-beta01 Box alignment is undefined. Using contentAlignment seems to work all the same. So many different ways of trying to do the same seemingly simple thing 😖
    – Victor Ude
    Feb 24, 2021 at 21:37
  • 1
    @VictorUde thanks for feedback. Answer updated. Mar 11, 2021 at 14:35
0

There is an even simpler solution without nesting:

@Composable
fun CenteredCircularProgressIndicator() = CircularProgressIndicator(
    Modifier
        .fillMaxSize()
        .wrapContentSize(Alignment.Center)
)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.