非Composable函数中如何获取stringResource?
解决Jetpack Compose中非Composable函数获取本地化字符串的问题
方法一:传递Context/Resources对象
在Composable函数中通过LocalContext.current获取Context,或者直接提取resources,将其作为参数传入非Composable函数,内部用context.getString(R.string.xxx)或resources.getString(R.string.xxx)获取本地化字符串:
// Composable调用处 @Composable fun DemoScreen() { val context = LocalContext.current Button(onClick = { handleNonComposableLogic(context) }) { Text(stringResource(R.string.btn_click)) } } // 非Composable函数 fun handleNonComposableLogic(context: Context) { val localizedText = context.getString(R.string.non_compose_text) // 后续业务逻辑处理 }
方法二:全局持有Resources实例(谨慎使用)
在自定义Application类中保存全局Resources对象,后续在非Composable函数中直接调用。但要注意,这种方式在配置变更(如语言切换)时,全局Resources不会自动更新,需手动处理:
class MyApplication : Application() { companion object { lateinit var appResources: Resources } override fun onCreate() { super.onCreate() appResources = this.resources } } // 非Composable函数中使用 fun nonComposableFunc() { val targetString = MyApplication.appResources.getString(R.string.target_str) }
方法三:转为Composable函数(若场景允许)
如果该非Composable函数的使用场景没有限制,直接添加@Composable注解,就能正常使用stringResource:
@Composable fun convertedComposableFunc() { val localizedStr = stringResource(R.string.converted_str) // 业务逻辑 }
内容的提问来源于stack exchange,提问作者LilMoke
相关产品推荐
相关产品推荐

