【问题标题】:Text Composable dimensionResource not working as fontSize parameter文本可组合尺寸资源不能用作 fontSize 参数
【发布时间】:2021-05-13 15:43:00
【问题描述】:

当我插入 fontSize = dimensionResource(id = R.dimen.textLabelTextSize) 时,dimens 或 54sp 或 60sp 取决于设备,我在 Text() 上收到错误“以下函数都不能用提供的论据。”但是当我输入一个像 54sp 这样的硬编码值时就很好了。奇怪的是填充修饰符 dimensionResource (in dp) 工作正常。

       Text(
                text = textLabelItem.textLabel,
                modifier = Modifier
                    .padding(
                        start = dimensionResource(id = R.dimen.textLabelPaddingVertical),
                        top = dimensionResource(id = R.dimen.textLabelPaddingHorizontalTop),
                        end = dimensionResource(id = R.dimen.textLabelPaddingVertical),
                        bottom = dimensionResource(id = R.dimen.textLabelPaddingHorizontalBottom)
                    )
                    .background(colorResource(id = R.color.textLabelBg))
                    .border(
                        width = 2.dp,
                        color = colorResource(id = R.color.textLabelBorder),
                        shape = RoundedCornerShape(8.dp)
                    ),
                color = colorResource(id = android.R.color.background_dark),
                fontSize = dimensionResource(id = R.dimen.textLabelTextSize),
                fontWeight = FontWeight.Bold
            )

【问题讨论】:

    标签: android kotlin android-resources android-jetpack-compose


    【解决方案1】:

    答案很简单,你只是忘了处理来自dimensionResource 的结果。您只需使用它的value 即可将其设为浮动。然后你使用sp 扩展,你就可以开始了。

    为此我创建了自己的扩展:

    @Composable
    @ReadOnlyComposable
    fun fontDimensionResource(@DimenRes id: Int) = dimensionResource(id = id).value.sp
    

    所以用dimensionResource(R.dimen.your_font_size)代替fontDimensionResource(R.dimen.your_font_size)

    最终解决方案:

    Text(text = "", fontSize = fontDimensionResource(id = R.dimen.your_font_size))
    

    【讨论】:

      【解决方案2】:

      dimensionResource 方法返回 dp 值。要从中获取sp 值,请在末尾添加.value.sp,如下所示:

      fontSize = dimensionResource(id = R.dimen.textLabelTextSize).value.sp

      【讨论】:

        【解决方案3】:

        这是因为函数 dimensionResource 返回一个 Dp 值,而 fontSizeSp 值一起使用。

        目前你不能使用它。

        【讨论】:

        • 如果我的dimen是54sp,为什么它会返回一个dp
        • @galaxigirl 因为该功能目前仅适用于 Dp。
        • 有什么想法如何使用不同的 sp 维度资源?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多