简体   繁体   English

如何在 JetpackCompose String 中访问复数资源

[英]How to access Plural resource in JetpackCompose String

I have the below我有以下

    <string name="loading_listing">Loading listings %d</string>
    <plurals name="loading_listing">
        <item quantity="one">Found %d listing</item>
        <item quantity="other">Found %d listings</item>
    </plurals>

If I use the string , as below all is okay如果我使用string ,如下所示一切都可以

Text(text = stringResource(R.string.loading_listing, 1))

But if I use the plurals ,但如果我使用plurals

Text(text = stringResource(R.plurals.loading_listing, 1))

it will crash它会崩溃

    android.content.res.Resources$NotFoundException: String resource ID #0x7f0d0003
        at android.content.res.Resources.getText(Resources.java:444)
        at android.content.res.Resources.getString(Resources.java:537)
        at android.content.res.Resources.getString(Resources.java:561)
        at androidx.compose.ui.res.StringResources_androidKt.stringResource(StringResources.android.kt:48)

I think it is not stringResource(...) that I can use.我认为我可以使用的不是stringResource(...) What is it then?之后怎么样了?

Meanwhile it's not available in Compose lib, you can create a helper function for that...同时它在 Compose lib 中不可用,您可以为此创建一个助手 function ...

@Composable
fun pluralResource(
    @PluralsRes resId: Int,
    quantity: Int,
    vararg formatArgs: Any? = emptyArray()
): String {
    return LocalContext.current.resources
        .getQuantityString(resId, quantity, *formatArgs)
}

With 1.xx there isn't a function to get a plural resource.对于1.xx ,没有 function 来获取复数资源。

You can use something like:你可以使用类似的东西:

val resources = LocalContext.current.resources

Text(
    text = resources.getQuantityString(
        R.plurals.loading_listing, 0, 10
    )
)

more complete solution:更完整的解决方案:

/**
 * Load a plurals resource.
 *
 * @param id the resource identifier
 * @param qty the associated quantity
 * @return the string data associated with the resource
 */
@Composable
@ReadOnlyComposable
fun pluralsResource(@PluralsRes id: Int, qty: Int): String {
    val resources = resources()
    return resources.getQuantityString(id, qty)
}

/**
 * Load a plurals resource with formatting.
 *
 * @param id the resource identifier
 * @param qty the associated quantity
 * @param formatArgs the format arguments
 * @return the string data associated with the resource
 */
@Composable
@ReadOnlyComposable
fun pluralsResource(@PluralsRes id: Int, qty: Int, vararg formatArgs: Any): String {
    val resources = resources()
    return resources.getQuantityString(id, qty, *formatArgs)
}

/**
 * A composable function that returns the [Resources]. It will be recomposed when [Configuration]
 * gets updated.
 */
@Composable
@ReadOnlyComposable
private fun resources(): Resources {
    LocalConfiguration.current
    return LocalContext.current.resources
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM