如何在Android Jetpack Compose中使用字符串资源?

61

假设我有以下的strings.xml资源文件:

<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 Compose中使用这些资源?

4个回答

102

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

字符串

你可以使用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()函数获取:

val planets = stringArrayResource(R.array.planets_array)

复数形式(数量字符串)

从compose 1.0.0-alpha10版本开始,没有内置的获取复数资源的函数,但是您可以通过LocalContext获取android上下文,并像在基于视图的应用程序中一样使用它。如果您创建类似于其他资源函数(例如Jetcaster compose示例)的自己的函数,则会更好:

// 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)

关于重组的说明

如您所知,在组合中,可组合函数可能会在重新组成期间被重新执行数百次。如果您构建的字符串不是简单的,并且需要一些计算,则最好记住计算结果,以便在每次重新组合时不会重新执行。例如:

...

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)
  )
}

3
关于重组,你确定在这个例子中需要“remember”吗?官方文档表明,如果可组合函数的参数保持不变,则不会对其进行重组:"通过跳过所有没有更改参数的函数或 lambda,Compose 可以高效地重新组合。" - Jonik

5

这里是一个例子:

Text(text = stringResource(id = R.string.myString)

即使导入后,我仍然遇到了字符串的问题。我正在使用一个多模块项目。 Text( text = stringResource(id = R.strings.welcome_text) ) - Josphat Mwania

3

从compose 1.2.0-alpha06 版本开始支持以下内容:

val likes = pluralStringResource(R.plurals.likes, 10, 10)

你能分享一下在 plurals.xml 中如何定义字符串吗? - Wafi_ck
@Wafi_ck 我把我的复数形式放在strings.xml中,使用与原始问题完全相同的语法。 - lt0
现在已经发布在1.2版本中 :) - DamienL

0
在可组合中使用这个。
LocalContext.current.getResources().getIdentifier()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接