There's androidx.compose.ui.res https://developer.android.com/reference/kotlin/androidx/compose/ui/res/package-summary包含用于加载字符串资源以及其他资源类型的函数的包。
string
您可以使用获取字符串stringResource() https://developer.android.com/reference/kotlin/androidx/compose/ui/res/package-summary#stringresource函数,例如:
...
import androidx.compose.ui.res.stringResource
@Composable
fun StringResourceExample() {
Text(
// a string without arguments
text = stringResource(R.string.app_name)
)
Text(
// a string with arguments
text = stringResource(R.string.greeting, "World")
)
}
字符串数组
可以使用获得stringArrayResource() https://developer.android.com/reference/kotlin/androidx/compose/ui/res/package-summary#stringarrayresource功能:
val planets = stringArrayResource(R.array.planets_array)
复数(数量字符串)
截至撰写1.0.0-alpha10
没有用于获取复数资源的内置函数,但您可以通过以下方式获取 android 上下文本地上下文 https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#localcontext并以与在基于视图的应用程序中使用相同的方式使用它。如果您创建自己的类似于其他函数的函数就更好了资源功能 (like 喷射机 https://github.com/android/compose-samples/tree/main/Jetcaster例如,撰写示例):
// PluralResources.kt
package com.myapp.util
import androidx.annotation.PluralsRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
@Composable
fun quantityStringResource(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): String {
return LocalContext.current.resources.getQuantityString(id, quantity, *formatArgs)
}
所以你可以用同样的方式使用它:
val likes = quantityStringResource(R.plurals.likes, 10, 10)
关于重组的注释
如您所知,在 compose 中,可组合函数可能每秒重新执行数百次重组 https://developer.android.com/jetpack/compose/mental-model#recomposition。如果您构建的字符串并不简单并且需要一些计算,那么最好remember https://developer.android.com/jetpack/compose/state#use-remember-to-store-immutable-values计算结果,因此不会在每次重组时重新执行。例如:
...
import androidx.compose.runtime.remember
@Composable
fun BirthdayDateComposable(username: String, dateMillis: Long) {
// formatDate() function will be executed only if dateMillis value
// is changed, otherwise the remembered value will be used
val dateStr = remember(dateMillis) {
formatDate(dateMillis)
}
Text(
text = stringResource(R.string.birthday_date, dateStr)
)
}