如何在AndroidJetpackCompose中使用字符串资源?

让我们有以下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 中使用这些资源?

回答

有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 上下文,并以与在基于视图的应用程序中相同的方式使用它。如果您创建自己的类似于其他资源函数的函数(例如Jetaster compose sample 所做的),那就更好了:

// 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 中,可组合函数在recomposition期间可能每秒重新执行数百次。如果你构建的字符串不是微不足道的,需要一些计算,最好记住计算结果,这样就不会在每次重新组合时重新执行。例如:

...

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


以上是如何在AndroidJetpackCompose中使用字符串资源?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>