You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose中Locale.getDefault()报错:无效引用问题求助

Jetpack Compose调用Locale.getDefault()报“无效引用”构建错误

学习Google Android Codelabs内容时,编写Jetpack Compose代码调用Locale.getDefault()出现构建错误,提示“无效引用”。相关代码片段如下:

val divider = "  •  "
val tagDivider = "  "
val text = buildAnnotatedString {
    append(post.metadata.date)
    append(divider)
    append(stringResource(R.string.read_time, post.metadata.readTimeMinutes))
    append(divider)
    post.tags.forEachIndexed { index, tag ->
        if (index != 0) {
            append(tagDivider)
        }
        append(" ${tag.uppercase(Locale.getDefault())} ")
    }
}

解决方法:

  • 检查并导入正确的Locale类
    确保代码顶部已导入java.util.Locale:

    import java.util.Locale
    
  • 使用Jetpack Compose推荐的Locale获取方式
    在Compose环境中,直接调用Locale.getDefault()可能因上下文或配置问题报错,推荐通过LocalConfiguration获取当前Locale,修改后的代码如下:

    // 先导入必要的包
    import androidx.compose.ui.platform.LocalConfiguration
    
    val divider = "  •  "
    val tagDivider = "  "
    val currentLocale = LocalConfiguration.current.locales[0]
    val text = buildAnnotatedString {
        append(post.metadata.date)
        append(divider)
        append(stringResource(R.string.read_time, post.metadata.readTimeMinutes))
        append(divider)
        post.tags.forEachIndexed { index, tag ->
            if (index != 0) {
                append(tagDivider)
            }
            append(" ${tag.uppercase(currentLocale)} ")
        }
    }
    
  • 同步并重建项目
    执行Gradle同步(File > Sync Project with Gradle Files),再依次执行Build > Clean Project和Build > Rebuild Project,确保代码变更和依赖生效。

内容的提问来源于stack exchange,提问作者robson idongesit samuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:39:24