【问题标题】:How to make Jetpack compose IconButton's width to adapt children's width?如何让 Jetpack 组合 IconButton 的宽度以适应儿童的宽度?
【发布时间】:2021-11-02 09:53:25
【问题描述】:

我想在图标下方创建一个带有文字的IconButton。我已经尝试将Modifier 中与宽度相关的方法应用于所有IconButtonColumnIconText。下面的代码是我得到的最接近的。结果看起来像this。而this 是我想要实现的目标。

@Composable
fun IconButtonWithTextBelow(
    title: String,
    @DrawableRes imageId: Int,
    onClick: () -> Unit
) {
    IconButton(
        onClick = onClick,
        modifier = Modifier.requiredWidth(IntrinsicSize.Max)
    ) {
        Column(
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.requiredWidth(IntrinsicSize.Max)
        ) {
            Icon(
                painter = painterResource(id = imageId),
                contentDescription = title,
            )
            Text(
                text = title,
            )
        }
    }
}

【问题讨论】:

    标签: android kotlin android-jetpack-compose iconbutton


    【解决方案1】:

    顾名思义,IconButton 仅用于显示Icon。即使你用静态大小修饰符增加容器的大小,你会发现点击时的波纹还是太小了。

    你可以使用TextButton,我可以使用Icon + Text,你只需要指定contentColorIconButton默认使用LocalContentColor.current,所以你也可以使用。

    TextButton(
        onClick = { /*TODO*/ },
        colors = ButtonDefaults.textButtonColors(contentColor = LocalContentColor.current)
    ) {
        Column(
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier
        ) {
            Icon(
                painter = painterResource(id = imageId),
                contentDescription = title,
            )
            Text(
                text = title,
            )
        }
    }
    

    但是TextButton 的实现在未来可能会改变,毕竟名字只说Text

    因此,更好的选择是在您的Column 上使用clickable 修饰符,也许padding。结果几乎是一样的。

    Column(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .padding(10.dp)
            .clickable(
                onClick = onClick,
                role = Role.Button,
            )
    ) {
        Icon(
            painter = painterResource(id = imageId),
            contentDescription = title,
        )
        Text(
            text = title,
        )
    }
    
    

    【讨论】:

      【解决方案2】:

      IconButton 的大小受 48.dp 限制,因此您需要实现自己的 IconButton。可以查看IconButton的源码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-29
        • 1970-01-01
        • 2014-05-07
        相关资源
        最近更新 更多