You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Android Plurals复数字符资源指定固定Locale规则

问题说明

我按照官方指引使用Android资源中的Plurals复数字符串,应用仅支持单一语言,希望无论设备当前设置的系统语言是什么,都固定使用应用目标语言的复数匹配规则,需要实现为Plurals复数字符资源指定Locale。
现有复数字符资源配置与调用代码如下:

<plurals name="amount_of_hours">
    <item quantity="zero">%d zero</item>
    <item quantity="one">%d one</item>
    <item quantity="two">%d two</item>
    <item quantity="few">%d few</item>
    <item quantity="many">%d many</item>
    <item quantity="other">%d other</item>
</plurals>
// 现有调用代码,需要给这个Plurals指定固定Locale
context.resources.getQuantityString(R.plurals.amount_of_hours, hours, hours)
实现方法

Android没有给单个Plurals资源单独指定Locale的API,系统匹配复数规则全看当前Context绑定的Locale,你只要构造一个绑定了目标Locale的专用Context,用它取复数字符串就行,具体步骤:

  • 写个Context扩展方法,生成绑定指定Locale的Context实例
fun Context.bindLocale(targetLocale: Locale): Context {
    val config = resources.configuration
    Locale.setDefault(targetLocale)
    config.setLocale(targetLocale)
    return createConfigurationContext(config)
}
  • 取Plurals的时候用这个绑定了固定Locale的Context,不要直接用原Context
// 替换成你应用的目标Locale即可,比如固定中文传Locale.CHINESE,固定英文传Locale.ENGLISH
val fixedContext = context.bindLocale(Locale.ENGLISH)
val hourText = fixedContext.resources.getQuantityString(R.plurals.amount_of_hours, hours, hours)

别直接修改Application或者Activity原本的Context配置,不然会打乱整个应用其他普通字符串、布局资源的匹配逻辑,这个临时生成的Context仅用来取固定规则的Plurals,用完就丢,不会产生额外副作用。

内容的提问来源于stack exchange,提问作者SoulReaver313

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 16:39:13