androidkotlinandroid-jetpack-composeandroid-toolbarandroid-jetpack-compose-material3

fillMaxSize() and textAlign don't work in toolbar jetpack compose


I have a toolbar having title "Shoes Marketplace", I want this title to be in centre.

My code:

Scaffold(

        containerColor = Color(33, 17, 52), // Set the overall background color of the Scaffold
        topBar = {
            TopAppBar(
                colors = TopAppBarDefaults.smallTopAppBarColors(
                    containerColor = Color(33, 17, 52),
                    titleContentColor = Color.White,
                ),
                title = {
                    Text(
                        "Shoes Marketplace",
                        textAlign = TextAlign.Center,
                        fontWeight = FontWeight.Bold,
                    )
                },
            )
        },
        modifier = Modifier.fillMaxSize()
    )

I have added textAlign= TextAlign.Center yet title text is not in centre.

textalign not working screenshot

If I add modifier=Modifier.fillMaxSize(), whole toolbar title disappears.

toolbar title disappearing

I checked official docs which does not have much information.


Solution

  • Here is a solution.

    when you title parameter in Scaffold it is by default wrapContentSize.

    so you need to make text fillMaxWidth() and it will take full width and now Align Paramter would work as expected.

    Output: preview

    Scaffold(
            containerColor = Color(33, 17, 52), // Set the overall background color of the Scaffold
            topBar = {
                TopAppBar(
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = Color(33, 17, 52),
                        titleContentColor = Color.White,
                    ),
                    title = {
                        Text(
                            "Shoes Marketplace",
                            textAlign = TextAlign.Center,
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier.fillMaxWidth()
                        )
                    },
                )
            },
            modifier = Modifier.fillMaxSize()
        ){
            Column (modifier = Modifier.padding(it)){
    
            }
        }