Android语言环境文件未加载。

3
该应用支持 8.0 及以上的操作系统。
我已经添加了支持 strings.xmlvalues-ar 文件夹。如果我将手机设置更改为阿拉伯语,应用程序会加载正确的资源。 如果我在 Application 类中运行时设置默认语言环境,则无法加载特定的(“ar”)资源。

d

这是我如何更改配置文件(在Application类中):

fun changeDefaultLocale() {
        Locale.setDefault(Locale("ar")
        val configuration = resources.configuration
        configuration.setLocale(locale)
        this.createConfigurationContext(configuration)
    }

我尝试过以下方法:

  • values-ar重命名为values-ar-rEG
  • app/build.gradle中添加resConfigs "en", "ar"
  • Manifest/<application中添加android:configChanges="locale"
  • 使用Locale("ar","AE")Locale("ar","EG")

我在调用上述changeDefaultLocale()函数后的下一行设置了断点:

enter image description here

为什么它不能加载正确的资源文件?我重复一遍,如果我从手机设置更改它,它就可以正常工作。
更新
使用@Nurbol的响应,我已经更新了BaseActivity如下,并且它正在正常工作。我的问题现在是:Activity A -> Activity B(在这里我切换语言环境),然后如果我按返回键并且系统恢复Activity A,则它具有旧的配置和旧的语言环境。如何克服这个问题?
override fun attachBaseContext(base: Context) {
    super.attachBaseContext(updateBaseContextLocale(base))
}

private fun updateBaseContextLocale(context: Context): Context {
    val locale = Locale("ar")
    Locale.setDefault(locale)
    return updateResourcesLocale(context, locale)
}

@TargetApi(Build.VERSION_CODES.N)
private fun updateResourcesLocale(context: Context, locale: Locale): Context {
    val configuration = context.resources.configuration
    configuration.setLocale(locale)
    return context.createConfigurationContext(configuration)
}

在这里找到了更新后的问题的答案。 - ghita
1个回答

0

程序中编程方式更改区域设置不建议使用,因为它容易出现错误。如果您真的想要更改它,您应该在每个活动的onCreate()方法中调用changeDefaultLocale()方法,在setContentView()之前执行。您可以简单地创建一个BaseActivity类来实现这一点,并将其用作每个活动的父类。

abstract class BaseActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Change locale settings in the app.
        val dm = resources.displayMetrics
        val conf = resources.configuration
        val lang = "ar"

        conf.setLocale(Locale(lang.toLowerCase())) // API 17+ only.

        resources.updateConfiguration(conf, dm)
    }
}

1
更新了我的回答。在@ghita处试用一下。 - Nurbol
它确实更改了rtl配置(因此布局从右到左切换),但仍然无法读取正确的strings.xml文件。我还在您的方法中添加了Locale.setDefault(Locale("ar"),但没有效果; - ghita
使用上面更新的代码。虽然已经过时,但在@ghita中仍然有效。 - Nurbol
谢谢你的回答Nurbol,我已经根据你的答案找到了解决方案,我已经更新了问题。 - ghita

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