Android 设置 APP 语言

541 阅读1分钟

7.0及以上版本

Activity中复写方法,修改resources配置,将Locale("ar")替换为你想要显示的语言

override fun attachBaseContext(newBase: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val configuration = newBase.resources.configuration
            configuration.setLocale(Locale("ar"))
            val localeList = LocaleList(Locale("ar"))
            configuration.setLocales(localeList)
            LocaleList.setDefault(localeList)
            super.attachBaseContext(newBase.createConfigurationContext(configuration))
        }else{
            super.attachBaseContext(newBase)
        }
    }

7.0以下版本

在 Activity 和 Application 中增加以下代码,将 Locale("ar") 替换为你想要显示的语言

       if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
           val configuration: Configuration = resources.configuration
           configuration.setLocale(Locale("ar"))
           configuration.setLayoutDirection(Locale("ar"))
           Locale.setDefault(Locale("ar"))
           resources.updateConfiguration(configuration, resources.displayMetrics)
       }

如果项目中没有使用Application.resources 获取文本资源(如toast提示中),Application 中可以不增加以上代码

setDefault() 方法不影响设置语言的效果,只是修改了Locale.getDefault()的值