如何减少jetpack中导航图标和标题之间的水平空间组成“TopAppBar”?

Pie*_*ira 10 android android-appbarlayout android-jetpack-compose

我正在 jetpack compose 中制作一个应用程序栏,但导航图标和标题之间存在间距问题。

这是我的撰写功能:

@Composable
fun DetailsAppBar(coin: Coin, backAction: () -> Unit) {
    TopAppBar(
        navigationIcon = {
            IconButton(onClick = { backAction() }) {
                Icon(
                    imageVector = Icons.Filled.ArrowBack,
                    contentDescription = null
                )
            }
        },
        title = { Text(text = "${coin.rank}. ${coin.name} (${coin.symbol})") }
    )
}
Run Code Online (Sandbox Code Playgroud)

这是我的预览功能:

@Composable
@Preview
fun DetailsAppBarPreview() {
    val bitcoin = Coin(
        id = "",
        isActive = true,
        name = "Bitcoin",
        rank = 1,
        symbol = "BTC"
    )
    DetailsAppBar(coin = bitcoin, backAction = {})
}
Run Code Online (Sandbox Code Playgroud)

这是我的撰写功能的视觉预览: 自定义应用栏预览

这是我要减少的空间:

应用栏中的空间减少

输入 compose 函数的代码,TopAppBar我看不到任何允许我执行此操作的参数。

Hen*_*nry 2

你是对的。对于您正在使用的变体TopAppBar,这是不可能的。这是因为 NavigationIcon 的宽度设置为默认值 (72.dp - 4.dp)。您可以检查它的实现TopAppBar并看到它使用以下内容:

private val AppBarHorizontalPadding = 4.dp

// Start inset for the title when there is a navigation icon provided
private val TitleIconModifier = Modifier.fillMaxHeight()
    .width(72.dp - AppBarHorizontalPadding)
Run Code Online (Sandbox Code Playgroud)

您可以做的是使用其他变体,TopAppBar它可以让您更好地控制标题和图标的放置。它可能是这样的:

@Composable
fun Toolbar(
    @StringRes title: Int,
    onNavigationUp: (() -> Unit)? = null,
) {
    TopAppBar(backgroundColor = MaterialTheme.colors.primary) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp)
        ) {
            // Title
            Text(...)
            
            // Navigation Icon
            if (onNavigationUp != null) {
                Icon(
                    painter = painterResource(id = R.drawable.ic_back),
                    contentDescription = stringResource(
                        id = R.string.back
                    ),
                    tint = MaterialTheme.colors.onPrimary,
                    modifier = Modifier
                        .clip(MaterialTheme.shapes.small)
                        .clickable { onNavigationUp() }
                        .padding(16.dp)
                        ...... ,
                )
            }
        }
    }
}

Run Code Online (Sandbox Code Playgroud)