I have a simple loading composable:
@Composable
fun Loading() {
CircularProgressIndicator()
}
I want it centered in the center of the screen. I've searched the docs and I've found layouts for building rows and columns, but I haven't found anything to center a view in the absolute middle of the screen.
How can be achieved?
First you need a view that takes up the whole screen, for that you need the fillMaxSize
modifier. In this case it can be a transparent Box
. Then you can center your view inside that container:
Box(
contentAlignment = Alignment.Center, // you apply alignment to all children
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center) // or to a specific child
)
}
In this case you can choose either of the two ways to set align
, I just mentioned it so you know for the future when you have multiple views inside a container.
A simpler solution, if you only need to layout a single view, is to use Modifier.wrapContentSize
.
In the case below, which gives the same result as the first solution, the parent will take the full available size (same as the box above), but the progress indicator won't follow this size and will only take as much as it needs, and will be placed in the center according to align
param.
CircularProgressIndicator(
modifier = Modifier
.fillMaxSize()
.wrapContentSize(align = Alignment.Center) // center is the default value so you can skip it
)