首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Android组合中使用字符串资源?

如何在Android组合中使用字符串资源?
EN

Stack Overflow用户
提问于 2021-01-25 16:53:15
回答 2查看 16.9K关注 0票数 34

让我们使用以下strings.xml资源文件:

代码语言:javascript
运行
复制
<resources>
    <!-- basic string -->
    <string name="app_name">My Playground</string>

    <!-- basic string with an argument -->
    <string name="greeting">Hello %!</string>

    <!-- plural string -->
    <plurals name="likes">
        <item quantity="one">%1d like</item>
        <item quantity="other">%1d likes</item>
    </plurals>

    <!-- string array -->
    <string-array name="planets">
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
</resources>

如何在Jetpack撰写中使用这些资源?

EN

回答 2

Stack Overflow用户

发布于 2021-01-25 16:53:15

有包含用于加载字符串资源以及其他资源类型的函数的androidx.compose.ui.res包。

字符串

可以使用stringResource()函数获得字符串,例如:

代码语言:javascript
运行
复制
...
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()函数获得:

代码语言:javascript
运行
复制
val planets = stringArrayResource(R.array.planets_array)

复数(数量字符串)

在编写1.0.0-alpha10时,没有内置的获取多元资源的功能,但是您可以通过LocalContext获取android上下文,并以与在基于视图的应用程序中使用它相同的方式使用它。更好的是,如果您创建自己的函数,类似于其他资源函数(例如,杰特卡斯特编写示例):

代码语言:javascript
运行
复制
// 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)
}

所以你可以用同样的方式:

代码语言:javascript
运行
复制
val likes = quantityStringResource(R.plurals.likes, 10, 10)

关于重组的一点注记

如您所知,在编写一个可组合函数时,可能会在重合期间以每秒数百次的速度重新执行。如果您构建的字符串并不简单,需要进行一些计算,最好是对计算结果进行记住,这样就不会在每次重新组合时重新执行它。例如:

代码语言:javascript
运行
复制
...

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)
  )
}
票数 59
EN

Stack Overflow用户

发布于 2022-04-01 20:15:44

现在,在编写1.2.0-alpha06时支持这一点。

代码语言:javascript
运行
复制
val likes = pluralStringResource(R.plurals.likes, 10, 10)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65889035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档