fillMaxSize() 和 textAlign 在工具栏 jetpack compose 中不起作用

问题描述 投票:0回答:2

我有一个标题为“Shoes Marketplace”的工具栏,我希望这个标题位于中心。

我的代码:

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()
    )

我已经添加了

textAlign= TextAlign.Center
,但标题文本不在中心。

如果我添加

modifier=Modifier.fillMaxSize()
整个工具栏标题就会消失。

我查了官方docs,没有太多信息。

android kotlin android-jetpack-compose android-toolbar android-jetpack-compose-material3
2个回答
0
投票

如果您想在文本上获得居中效果,您应该将其包装在

@Composable
布局中。

例如

选择您的代码并简单地添加一个

Row
它将是:

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 = {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center) {
                    Text(
                        "Shoes Marketplace",
                        textAlign = TextAlign.Center,
                        fontWeight = FontWeight.Bold,
                    )
                }
            },
        )
    },
    modifier = Modifier.fillMaxSize()
)

基本上几种布局都可以获得相同的效果,不一定非要一个

Row
.

希望它有所帮助,编码愉快! :)


0
投票

这里有一个解决方案。

当您在

title
中使用
Scaffold
参数时,默认为
wrapContentSize

因此您需要制作文本

fillMaxWidth()
,它将采用全宽,现在
Align
参数将按预期工作。

输出:

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)){

        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.