Android应用动态切换语言配置

Android示例项目集合
2021-05-17 14:29 · 阅读时长3分钟
小课

在Android开发中,我们会根据需求配置一些多语言资源,比如values-en,values-zh,默认情况下,系统会根据当前手机的语言配置去获取对应的资源文件,我们不需要做任何操作,但是如果我们想要动态修改应用所使用的语言资源,就需要手动去修改当前应用的语言配置。

在API 17和API 24中对这部分都做了改动,所以在处理的时候要注意兼容不同的版本,下面看看修改语言的核心代码。

1fun localeWrap(context: Context, newLocale: Locale): ContextWrapper {
2    val res = context.resources
3    val configuration = res.configuration
4    val newContext = when {
5        Build.VERSION.SDK_INT >= 24 -> {
6            configuration.setLocale(newLocale)
7            val localeList = LocaleList(newLocale)
8            LocaleList.setDefault(localeList)
9            configuration.setLocales(localeList)
10            context.createConfigurationContext(configuration)
11        }
12        Build.VERSION.SDK_INT >= 17 -> {
13            configuration.setLocale(newLocale)
14            context.createConfigurationContext(configuration)
15        }
16        else -> {
17            configuration.locale = newLocale
18            res.updateConfiguration(configuration, res.displayMetrics)
19            context
20        }
21    }
22    return ContextWrapper(newContext)
23}

我们可以在设置中将选择的语言保存在preferences中,然后在Activity的attachBaseContext方法中获取设置的语言并使用。

override fun attachBaseContext(newBase: Context) {
    val preferences = newBase.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    super.attachBaseContext(
        localeWrap(
            newBase,
            Locale(preferences.getString(LOCALE_KEY, "en")!!)
        )
    )
}

下面是以上示例代码完整的项目。

文件大小修改时间
app
2022年05月09日
build.gradle
358 B 2022年05月09日
gradle/wrapper
2022年05月09日
gradle.properties
1 kB 2022年05月09日
gradlew
6 kB 2022年05月09日
gradlew.bat
3 kB 2022年05月09日
local.properties
434 B 2022年05月09日
settings.gradle
325 B 2022年05月09日