如何更改 Jetpack Compose 中的 TopAppBar 位置

How can I change TopAppBar position in the jetpack compose

我想把“账户”的文字设置到TopAppBar的中间,并在TopAppBar的右侧添加一个图标,怎么办?

 Scaffold(
        scaffoldState = scaffoldState,
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = stringResource(R.string.account),
                        style = AppFont.PoppinsTypography.subtitle1
                    )
                },
                navigationIcon = {
                    Icon(
                        painter = painterResource(id = R.drawable.ic_left),
                        contentDescription = "back", tint = AppColor.brandColor.BLUE_DE_FRANCE
                    )
                }, actions = {
                    viewModel.navigateUp()
                }, backgroundColor = AppColor.neutralColor.DOCTOR
            )
        },
    )

将标题文本与 TopAppbar

的中心对齐

title改成这样,

title = {
    Text(
        text = stringResource(R.string.account),
        textAlign = TextAlign.Center,
        modifier = Modifier.fillMaxWidth(),
        style = AppFont.PoppinsTypography.subtitle1
    )
},

actions 属性应该在末尾添加可组合项。使用它在 TopAppBar.

的右侧添加一个图标

示例,

actions = {
    IconButton(onClick = { /*TODO*/ }) {
        Icon(
            imageVector = Icons.Rounded.ShoppingCart,
            contentDescription = "cart",
        )
     }
 },

您可以实现自定义布局


@Composable
fun TopBar() {
    Scaffold(
        topBar = {
            Layout(
                modifier = Modifier.fillMaxHeight(0.1f), //Fills one-tenth of the screen
                content = {
                    Text("Account")

                    Icon(
                        imageVector = Icons.Default.ArrowBack,
                        contentDescription = "back",
                        tint = Color.Blue,
                    )
                }
            ) { measurables, constraints ->

                val title = measurables[0].measure(constraints)
                val navigationIcon = measurables[1].measure(constraints)

                layout(constraints.maxWidth, constraints.maxHeight) {

                    title.place(
                        (constraints.maxWidth - title.width) / 2, //Midway
                        constraints.maxHeight / 2 // Usually Texts acquire maxHeight so we did not need t subtract
                    )

                    navigationIcon.place(
                        (constraints.maxWidth - 1.5 * navigationIcon.width).roundToInt(), //1.5 to add a bit of extra padding from the edge
                        (constraints.maxHeight - navigationIcon.height) / 2
                    )

                }
            }
        },
    ) {

    }
}