Jetpack Compose中使用Object类时如何从XML文件获取字符串?
解决方法
你用LocalContext.current失效的核心原因是:这个API只能在带@Composable注解的函数内部使用,而你的Apples是普通object类,不在Compose的上下文作用域里,所以无法获取有效上下文。
下面是具体实现步骤:
1. 在XML中定义字符串数组
先在res/values/strings.xml里添加字符串数组资源:
<resources> <!-- 可选:单独定义每个颜色字符串,便于统一维护 --> <string name="apple_red">red</string> <string name="apple_yellow">yellow</string> <string name="apple_green">green</string> <!-- 定义字符串数组 --> <string-array name="apple_colors"> <item>@string/apple_red</item> <item>@string/apple_yellow</item> <item>@string/apple_green</item> </string-array> </resources>
2. 根据使用场景选择获取方式
场景1:在Composable函数中使用
直接在Compose组件内获取数组并转换为List:
@Composable fun AppleListScreen() { val context = LocalContext.current // 从资源中读取字符串数组并转为List val appleColors = context.resources.getStringArray(R.array.apple_colors).toList() // 示例:渲染颜色列表 LazyColumn { items(appleColors) { color -> Text(text = color) } } }
场景2:保留Apples object类
将硬编码的List改为需要传入Context的方法,使用时传入有效上下文:
object Apples { // 传入Context获取颜色列表 fun getColors(context: Context): List<String> { return context.resources.getStringArray(R.array.apple_colors).toList() } } // 在Activity中调用 val colors = Apples.getColors(this) // 在Compose中调用 val context = LocalContext.current val colors = Apples.getColors(context)
场景3:全局使用Application Context
如果需要在非UI类中也能获取,可通过Application类持有全局上下文:
// 自定义Application类,记得在AndroidManifest.xml的<application>标签中指定android:name=".MyApplication" class MyApplication : Application() { companion object { lateinit var appContext: Context } override fun onCreate() { super.onCreate() appContext = applicationContext } } // 修改Apples类 object Apples { val colors get() = MyApplication.appContext.resources.getStringArray(R.array.apple_colors).toList() } // 直接调用即可 val appleColors = Apples.colors
内容的提问来源于stack exchange,提问作者Mister Propre
相关产品推荐
相关产品推荐

