• Android应用内设置多语言


    1、项目简介

    最近项目中要加入多语言需求,涉及到的有中文简体,中文繁体,英语,西班牙语,泰语,印尼语,葡萄牙语。参考了Android应用内设置多语言,可随系统语言改变而改变,在此基础上做了修改,选择为跟随系统时不再粗暴调用 此方法。android.os.Process.killProcess(android.os.Process.myPid());
    直接杀死会有一个类似于崩溃的效果,产品上难以接受。所以跟随系统时查看系统语言单独调用,如果本地string中不存在系统语言对应的语言,那么默认为英语。下面看一下效果图:
    因为目前只有一个MainActivity页面,选择语言后切换跳转有闪动,大家可以切换语言后回到首页,就像微信切换语言一样。


     

     2、实现原理

    首先在res下创建对应的string对应语言文件

    在Application中调用attachBaseContext方法中的初始化,如果本地有sp保存的语言,显示此语言,如果没有就显示系统语言。

    1. protected void attachBaseContext(Context base) {
    2. //系统语言等设置发生改变时会调用此方法,需要要重置app语言
    3. super.attachBaseContext(MultiLanguageUtil.attachBaseContext(base));
    4. }
    1. @TargetApi(Build.VERSION_CODES.N)
    2. private static Context createConfigurationResources(Context context) {
    3. Resources resources = context.getResources();
    4. Configuration configuration = resources.getConfiguration();
    5. Locale appLocale = getAppLocale(context);
    6. Log.i("language0", appLocale.getLanguage() + "--------" + appLocale.getCountry() + "--------" + appLocale.toLanguageTag());
    7. Constants.SYSTEM_LANGUAGE = appLocale.getLanguage();
    8. Constants.SYSTEM_COUNTRY = appLocale.getCountry();
    9. Constants.SYSTEM_TOLANGUAGETAG = appLocale.toLanguageTag();
    10. //如果本地有语言信息,以本地为主,如果本地没有使用默认Locale
    11. Locale locale = null;
    12. String spLanguage = SPUtils.getLanguageString(context, Constants.LOCALE_LANGUAGE);
    13. String spCountry = SPUtils.getLanguageString(context, Constants.LOCALE_COUNTRY);
    14. if (!TextUtils.isEmpty(spLanguage) && !TextUtils.isEmpty(spCountry)) {
    15. if (isSameLocal(appLocale, spLanguage, spCountry)) {
    16. locale = appLocale;
    17. } else {
    18. locale = new Locale(spLanguage, spCountry);
    19. }
    20. } else {
    21. if (Constants.SYSTEM_TOLANGUAGETAG.contains("zh-Hant")) {
    22. locale = new Locale(Constants.SYSTEM_LANGUAGE, "TW");
    23. } else if (Constants.SYSTEM_TOLANGUAGETAG.contains("zh-Hans") || Constants.SYSTEM_TOLANGUAGETAG.equals("zh-CN")) {
    24. locale = new Locale(Constants.SYSTEM_LANGUAGE, "CN");
    25. } else {
    26. locale = appLocale;
    27. }
    28. }
    29. configuration.setLocale(locale);
    30. configuration.setLocales(new LocaleList(locale));
    31. return context.createConfigurationContext(configuration);
    32. }

    在MainActivity主页面initData()方法中显示sp存储过对应的语言,如果为空,那么就选中系统语言

    1. if (!TextUtils.isEmpty(spLanguage) && !TextUtils.isEmpty(spCountry)) {
    2. if(spLanguage.equals("zh") && spCountry.equals("CN")){
    3. rbgroup.check(rb1.getId());
    4. } else if(spLanguage.equals("zh") && spCountry.equals("TW")){
    5. rbgroup.check(rb2.getId());
    6. }else if(spLanguage.equals("en") && spCountry.equals("US")){
    7. rbgroup.check(rb3.getId());
    8. }else if(spLanguage.equals("es") && spCountry.equals("ES")){
    9. rbgroup.check(rb4.getId());
    10. }else if(spLanguage.equals("th") && spCountry.equals("TH")){
    11. rbgroup.check(rb5.getId());
    12. }else if(spLanguage.equals("in") && spCountry.equals("ID")){
    13. rbgroup.check(rb6.getId());
    14. }else if(spLanguage.equals("pt") && spCountry.equals("PT")){
    15. rbgroup.check(rb7.getId());
    16. }
    17. } else {
    18. rbgroup.check(rb0.getId());
    19. }

    然后选中语言和取消选中采用的是RadioGroup和RadioButton,选中一种语言设置与之对应的语言和地区

    1. rbgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    2. @Override
    3. public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
    4. if (checkId == rb0.getId()) {
    5. String language = Constants.SYSTEM_LANGUAGE;
    6. if (language.equals("zh") && (Constants.SYSTEM_TOLANGUAGETAG.contains("zh-Hans") || Constants.SYSTEM_TOLANGUAGETAG.equals("zh-CN"))) {
    7. changeLanguage("zh", "CN",false); //中文简体
    8. } else if (language.equals("zh") && Constants.SYSTEM_TOLANGUAGETAG.contains("zh-Hant")) {
    9. changeLanguage("zh", "TW",false);//中文繁体
    10. } else if (language.equals("en")) {
    11. changeLanguage("en", "US",false); //英语---默认系统语言
    12. } else if (language.equals("es")) {
    13. changeLanguage("es", "ES",false); //西班牙
    14. } else if (language.equals("th")) {
    15. changeLanguage("th", "TH",false);// 泰语
    16. } else if (language.equals("in")) {
    17. changeLanguage("in", "ID",false);// 印度尼西亚语
    18. } else if (language.equals("pt")) {
    19. changeLanguage("pt", "PT",false);// 葡萄牙
    20. } else {
    21. changeLanguage("en", "US",false); //英语---默认系统语言
    22. }
    23. } else if (checkId == rb1.getId()) {
    24. changeLanguage("zh", "CN",true); //中文简体
    25. } else if (checkId == rb2.getId()) {
    26. changeLanguage("zh", "TW",true);//中文繁体
    27. } else if (checkId == rb3.getId()) {
    28. changeLanguage("en", "US",true); //英语---默认系统语言
    29. } else if (checkId == rb4.getId()) {
    30. changeLanguage("es", "ES",true); //西班牙
    31. } else if (checkId == rb5.getId()) {
    32. changeLanguage("th", "TH",true);// 泰语
    33. } else if (checkId == rb6.getId()) {
    34. changeLanguage("in", "ID",true);// 印度尼西亚语
    35. } else if (checkId == rb7.getId()) {
    36. changeLanguage("pt", "PT",true);// 葡萄牙
    37. }
    38. }
    39. });

    在此处我做的改进是当选中的是系统语言时,判断此时的系统语言是哪种,然后设置与之对应的方法,英语为默认语言。

    1. //修改应用内语言设置
    2. private void changeLanguage(String language, String area,boolean noSystemLanguage) {
    3. if(!noSystemLanguage){
    4. SPUtils.saveLanguageString(MainActivity.this,Constants.LOCALE_LANGUAGE, "");
    5. SPUtils.saveLanguageString(MainActivity.this,Constants.LOCALE_COUNTRY, "");
    6. }
    7. //不为空,那么修改app语言,并true是把语言信息保存到sp中,false是不保存到sp中
    8. Locale newLocale = new Locale(language, area);
    9. MultiLanguageUtil.changeAppLanguage(MainActivity.this, newLocale, noSystemLanguage);
    10. //重启app,这一步一定要加上,如果不重启app,可能打开新的页面显示的语言会不正确
    11. Intent intent = new Intent(MainActivity.this, MainActivity.class);
    12. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    13. startActivity(intent);
    14. finish();
    15. }

    如果为系统语言,sp不再存储数据,反之存储对应的语言数据,如果选择为英语,默认设置为Locale.ENGLISH

    1. public static void changeAppLanguage(Context context, Locale locale, boolean persistence) {
    2. Resources resources = context.getResources();
    3. DisplayMetrics metrics = resources.getDisplayMetrics();
    4. Configuration configuration = resources.getConfiguration();
    5. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    6. if (locale.getLanguage().equals("en")) {
    7. configuration.setLocale(Locale.getDefault());
    8. configuration.setLocale(Locale.ENGLISH);
    9. } else {
    10. configuration.setLocale(locale);
    11. configuration.setLocales(new LocaleList(locale));
    12. }
    13. context.createConfigurationContext(configuration);
    14. } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    15. configuration.setLocale(locale);
    16. } else {
    17. configuration.locale = locale;
    18. }
    19. resources.updateConfiguration(configuration, metrics);
    20. if (persistence) {
    21. SPUtils.saveLanguageString(context, Constants.LOCALE_LANGUAGE, locale.getLanguage());
    22. SPUtils.saveLanguageString(context, Constants.LOCALE_COUNTRY, locale.getCountry());
    23. }
    24. }

    到此处多语言中主要方法已经介绍完了,希望给予有需要的同学一些帮助,如果有什么疑问欢迎评论留言。最后附上多语言demo  点击下载

    最全的android各国语言对照表
    在线翻译--多语言

     

    多语言适配遇到问题以及解决
    1、切换本地语言后杀死 app 重新进入,查看帖子详情以及发帖等页面某些数据 无法正确对应本地设置的语言。原因在于项目升级到 AndroidX 版本,Appcompat
    1.2+版本导致多语言切换失败,Androidx(appcompat:1.2.0) 中包装了一层
    ContextThemeWrapper,但就是因为给包的这一层逻辑有问题,导致了多语言切
    换时效。
    该包装方法实现了两套逻辑:
    1、传入的 context 是经过 ContextThemeWrapper 封装的,则直接使用该
    context 配置(包含语言)进行覆盖
    2、传入的 context 未经过 ContextThemeWrapper 封装,则从
    PackageManger 中获取配置(包含语言),然后和传入的 context 配置(包含语言)
    进行对比,并新创建了一个 configration 对象,如果两者有对比不同的配置则
    赋值给这个 configration,如果相同则跳过,最后将这个新建的 configration
    作为最终配置结果进行覆盖。
    而多语言问题就出现在 [2] 这套逻辑上,如果 PackageManager 与 传入的
    context 某个配置项一致时就不会给新建的 configration 赋值该配置项。这就
    会导致当这一次切换成功后,杀死进程下次启动时,由于 packageManager 配置
    的语言 与 context 配置的语言一致,而直接跳过,并没有给新建的
    configration 进行赋值,最终表现就是多语言失效。
    所以需要在 BaseActivity 手动再给包一层 ContextThemeWrapper:
     
    1. protected void attachBaseContext(Context newBase) {
    2. //切换多语言,然后将新生成的 context 覆盖给 attachBaseContext()
    3. Context context = MultiLanguageUtils.changeContextLocale(newBase);
    4. //兼容 appcompat 1.2.0 后切换语言失效问题
    5. final Configuration configuration = context.getResources().getConfiguration();
    6. final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context,
    7. R.style.Base_Theme_AppCompat_Empty) {
    8. public void applyOverrideConfiguration(Configuration overrideConfiguration) {
    9. if (overrideConfiguration != null) {
    10. overrideConfiguration.setTo(configuration);
    11. }
    12. super.applyOverrideConfiguration(overrideConfiguration);
    13. }
    14. };
    15. super.attachBaseContext(wrappedContext);
    16. }
    这样就很好的解决了整个应用切换语言后重新进入某些数据多语言失效的问题。​​​​​​​
  • 相关阅读:
    【C语言】每日一题(半月斩)——day1
    Django(三)接口自动化平台HttpRunnerManager本地部署
    知识点终结
    小程序门店自提功能,提高线上线下销售量
    [极致用户体验] 为什么建议2022年不用“等比设计稿“+rem,而用“灵活设计稿“+px
    速盾网络:CDN用几天关了可以吗?安全吗?
    (免费分享)基于springboot论坛bbs系统
    字节跳动基于ClickHouse优化实践之“多表关联查询”
    【计算机视觉 05】YOLO论文讲解:V1-V7
    python中的Frame对象初探
  • 原文地址:https://blog.csdn.net/lou_liang/article/details/126390461