程序员Android开发

Android 多语言切换,适配8.0

2018-09-11  本文已影响0人  天青色等Y雨

\color{#000042}{Android多语言切换其实就是创建不同语言的带后缀的values文件夹,将}
\color{#000042}{App中需要中英文切换的文字写在不同values文件夹下的strings.xml中,}
\color{#000042}{以中英文切换为例:}


image.png res目录下文件

\color{#FF0000}{values目录下的strings.xml文件的部分内容:}

    <string name="search_pathogens">病原体搜索</string>
    <string name="pathogens">病原体</string>
    <string name="virus">病毒</string>
    <string name="bacteria">细菌</string>
    <string name="fungus">真菌</string>
    <string name="others">其他</string>
    <string name="collection">收藏</string>

\color{#FF0000}{values-en目录下的strings.xml文件的部分内容:}

    <string name="search_pathogens">Search for pathogens</string>
    <string name="pathogens">Pathogens</string>
    <string name="virus">Virus</string>
    <string name="bacteria">Bacteria</string>
    <string name="fungus">Fungus</string>
    <string name="others">Others</string>
    <string name="collection">Collection</string>
 // 获得res资源对象
Resources resources = activity.getResources();
// 获得屏幕参数:主要是分辨率,像素等。
DisplayMetrics metrics = resources.getDisplayMetrics();
// 获得配置对象
Configuration config = resources.getConfiguration();
//区别17版本(其实在17以上版本通过 config.locale设置也是有效的,不知道为什么还要区别)
//在这里设置需要转换成的语言,也就是选择用哪个values目录下的strings.xml文件
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      config.setLocale(Locale.SIMPLIFIED_CHINESE);//设置简体中文
      //config.setLocale(Locale.ENGLISH);//设置英文
  } else {
      config.locale = Locale.SIMPLIFIED_CHINESE;//设置简体中文
      //config.locale = Locale.ENGLISH;//设置英文
  }
resources.updateConfiguration(config, metrics);

\color{#000042}{ 注意:在获取Resources对象时,所传的Context在Android8.0以下可以是}
\color{#000042}{Activity或者是Application;但是在8.0以上,只能是Activity,否则切换无效}


//调完这个之后,文字就会变成你设置的其他语言了                    
tvFungus.setText(getResources().getString(R.string.fungus));

\color{#000042}{注:app关闭之后是会自动切换到手机系统语言的,所以在app退出之前如果设}
\color{#000042}{置成了英文,app重新打开还是会显示中文,所以想要在重新打开app时依旧显}
\color{#000042}{示英文,就需要在每次修改完语言状态之后通过sharedPreference进行状态保}
\color{#000042}{存,然后在app首页进行语言设置(不要在application里设置,因为还要适配8.0)}


\color{#000042}{········何为生活,不想喝的酒,先干为敬;不想见的人,笑脸相迎········}


上一篇 下一篇

猜你喜欢

热点阅读