如何在 Jetpack Compose 中传递条件参数?

Gus*_*ria 3 android android-jetpack android-jetpack-compose android-compose-appbar

我想隐藏navigationIcon,但是当我通过nullUnit图标空间仍然可见时,如下图所示。

菜单预览

@Composable
fun DefaultScaffold(
    title: String? = null,
    icon: ImageVector? = null,
    content: @Composable() () -> Unit
) {
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    if (title != null) {
                        Text(text = "My Title")
                    }
                },
                navigationIcon = {
                    if (icon != null) {
                        IconButton(
                            onClick = {}
                        ) {
                            Icon(imageVector = Icons.Filled.Close, contentDescription = null)
                        }
                    } else Unit
                }
            )
        }
    ) {
        content()
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*aga 6

删除条件语句周围的括号,然后在您不想显示图标空间时返回null而不是返回。Unit

那么,就会变成

navigationIcon = if (icon != null) {
    {
        IconButton(
            onClick = {}
        ) {
            Icon(imageVector = Icons.Filled.Close, contentDescription = null)
        }
    }
} else null
Run Code Online (Sandbox Code Playgroud)


Gab*_*tti 5

你可以使用类似的东西

navigationIcon = if (icon != null) {
    { /*... your code ..*/ }
} else null
Run Code Online (Sandbox Code Playgroud)

TopAppBar但withtitle和parameters的构造函数navigationIcon保留了标题和导航图标的插槽。如果你检查源代码你可以发现:

if (navigationIcon == null) {
            Spacer(TitleInsetWithoutIcon)
        } else {
Run Code Online (Sandbox Code Playgroud)

您应该使用带有参数的构造函数content,其内容没有限制。
然后你可以使用类似的东西:

    TopAppBar(
        content = {
            Row(Modifier.fillMaxHeight(), verticalAlignment = Alignment.CenterVertically){
                if (icon != null) {
                    IconButton(
                        onClick = {},
                    ) {
                        Icon(imageVector = icon, contentDescription = null)
                    }
                }
                if (title != null) {
                    ProvideTextStyle(value = MaterialTheme.typography.h6) {
                        CompositionLocalProvider(
                            LocalContentAlpha provides ContentAlpha.high,
                        ){
                            Text(text = title)
                        }
                    }
                }
            }
        }
    )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述