Search code examples
androidandroid-jetpack-composeandroid-jetpack-compose-text

Jetpack Compose align Text content to center of the Scaffold


My Problem:

I want to place my Text() content to center of the page in Scaffold.

I tried "textAlign = TextAlign.Center" - It align the text in horizontal area alone. Not align the text in vertical area.

My code:

@Composable
fun ScaffoldWithTopBar() {
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(text = "Top App Bar")
                },
                navigationIcon = {
                    IconButton(onClick = {}) {
                        Icon(Icons.Filled.ArrowBack, "backIcon")
                    }
                },
                backgroundColor = MaterialTheme.colors.primary,
                contentColor = Color.White,
                elevation = 10.dp
            )
        }, content = {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color(0xff8d6e63)),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {

            }
            Text(
                text = "Content of the page",
                fontSize = 30.sp,
                color = Color.White
            )
        })
}

Note: I haven't place this text into Column. I used directly.

My output:

enter image description here

Question: How to place the text into the center of the parent?


Solution

  • Assign the fillMaxSize() to the parent container, not to the Text:

       Box(Modifier.fillMaxSize(),
           contentAlignment = Center
       ) {
           Text(
               text = "Content of the page",
               fontSize = 30.sp,
               modifier = Modifier
                   .background(Color(0xffb3e5fc)),
           )
       }
    

    or:

    Column(Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Content of the page",
            fontSize = 30.sp,
            modifier = Modifier
                .background(Color(0xffb3e5fc)),
        )
    }
    

    enter image description here