android - 文本可组合尺寸资源不能用作 fontSize 参数

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

当我插入 fontSize = dimensionResource(id = R.dimen.textLabelTextSize) 时,dimens 或 54sp 或 60sp 取决于设备,我在 Text() 上收到错误“不能使用提供的参数调用以下函数。 "但是当我输入一个像 54sp 这样的硬编码值时就很好了。奇怪的是填充修饰符 dimensionResource(在 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
            )

最佳答案

答案很简单,你只是忘了处理 dimensionResource 的结果。 .您只需使用 value让它作为 float 。然后你使用 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))

关于android - 文本可组合尺寸资源不能用作 fontSize 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67522145/

相关文章:

android - 如何强制应用进入全屏模式(切入友好状态)

java - 在ListView上依次显示用户信息

android - 严格模式 : StrictModeDiskReadViolation when creating SharedPreference

android - 如何从 Android RoomDB 中的字符串列表中查询特定字符串

android - 不确定如何将游标转换为此方法返回类型

android - 为什么以及如何在 Android Studio 中使用 @xml/file_paths 资源?

Android 添加 "values-en"文件夹导致 "Couldn' t 解析资源”警告

android - Gson 。将带有字符 = 的密码转换为 JSON

android - 我可以将我的 android 项目中的资源标记为已弃用吗?

android - 如何防止用户通过设置菜单禁用我的设备管理应用程序?