如果是单独给app加上国际化,其实很容易,创建对应的国家资源文件夹即可,如values-en,values-pt,app会根据当前系统语言去使用对应语言资源文件,如果找不到,则使用values文件夹里的资源。但本文讲得是另外一种情况,就是app内置一个切换多语言的页面,可以给用户切换。
<!-- 国际化多语言 --> <service android:name="androidx.appcompat.app.AppLocalesMetadataHolderService" android:enabled="false" android:exported="false"> <meta-data android:name="autoStoreLocales" android:value="true" /> </service>2.在xml文件夹增加文件locale_config.xml
<locale-config xmlns:android="http://schemas.android.com/apk/res/android"> <locale android:name="en" /> <locale android:name="pt" /> <locale android:name="es" /> <locale android:name="de" /> <locale android:name="fr" /> </locale-config>3.调用方法切换多语言
// 切换语言 val langua="en" AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(langua))补充下其他方法:
//获取当前应用使用语言 val locale = AppCompatDelegate.getApplicationLocales()[0] //语言短标转为locale对象 val langua="en" val locale = Locale.forLanguageTag(langua)
buildTypes { release { bundle{ //设置多语言不分包处理 language { // Specifies that the app bundle should not support // configuration APKs for language resources. These // resources are instead packaged with each base and // feature APK. enableSplit = false } density { // This property is set to true by default. enableSplit = true } abi { // This property is set to true by default. enableSplit = true } } } }2.使用StringUtil导致语言切换功能失效