转载请注明出处 http://www.cnblogs.com/cnwutianhao/p/6746981.html

前几天客户提需求,对App增加一个功能,这个功能目前市面上已经很常见,那就是应用内切换语言。啥意思,就是 英、中、法、德、日。。。语言随意切换。

(本案例采用Data-Bingding模式,麻麻再也不用担心我findViewBy不到Id了哈哈,开个玩笑)

先上示例图:

代码实现:

布局文件(Data-Binding模式),很简单就是两行文字

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"> <RelativeLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tnnowu.android.switchlanguage.MainActivity"> <TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/title"
android:textSize="30sp"
android:textStyle="bold" /> <TextView
android:id="@+id/descTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/titleTextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="@string/desc"
android:textSize="20sp" /> </RelativeLayout> </layout>

从实例中我们可以看到右上角是有Menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity"> <item
android:id="@+id/language_english"
android:orderInCategory="100"
android:title="@string/menu_english" />
<item
android:id="@+id/language_simplified_chinese"
android:orderInCategory="100"
android:title="@string/menu_simplified_chinese" />
<item
android:id="@+id/language_turkish"
android:orderInCategory="100"
android:title="@string/menu_turkish" />
<item
android:id="@+id/language_japanese"
android:orderInCategory="100"
android:title="@string/menu_japanese" /> </menu>

(既然是多语言,所以就要有N个strings)

,本案例我创建了4种语言。

好的,Menu的布局写完了,接下来就是实现Menu功能,记住实现Menu就两套代码,一个 onCreateOptionsMenu , 另一个是 onOptionsItemSelected 。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.language_english) {
updateViews("en");
} else if (id == R.id.language_simplified_chinese) {
updateViews("zh");
} else if (id == R.id.language_turkish) {
updateViews("tr");
} else if (id == R.id.language_japanese) {
updateViews("ja");
}
return super.onOptionsItemSelected(item);
}

在这里,可以看到,我们自定义一个 updateViews() 方法,用来实现切换预言时界面的改变

private void updateViews(String languageCode) {
Context context = LocaleHelper.setLocale(this, languageCode);
Resources resources = context.getResources(); mBinding.titleTextView.setText(resources.getString(R.string.title));
mBinding.descTextView.setText(resources.getString(R.string.desc)); setTitle(resources.getString(R.string.toolbar_title));
}

公布一个 语言判断的类 LocaleHelper

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, lang);
} public static Context onAttach(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
return setLocale(context, lang);
} public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
} public static Context setLocale(Context context, String language) {
persist(context, language); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
} return updateResourcesLegacy(context, language);
} private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
} private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit(); editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
} @TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale); Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale); return context.createConfigurationContext(configuration);
} @SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration();
configuration.locale = locale; resources.updateConfiguration(configuration, resources.getDisplayMetrics()); return context;
}
}

最后还要做的操作就是,自定义一个Application类,用来设定App的默认语言(当然了,要将这个Application应用到Manifest中)

public class BaseApplication extends Application {

    @Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
} }

本案例实现App内语言切换代码量不大,通俗易懂,无垃圾代码。

示例代码下载地址:App内切换语言

关注我的新浪微博,请认准黄V认证,获取最新安卓开发资讯。

关注科技评论家,领略科技、创新、教育以及最大化人类智慧与想象力!

App内切换语言的更多相关文章

  1. 解决Android 7.0 App内切换语言不生效的问题

    Android7.0及以前版本,Configuration中的语言相当于是App的全局设置: public static void changeAppLanguage(Context context, ...

  2. IOS APP 国际化 程序内切换语言实现 不重新启动系统(支持项目中stroyboard 、xib 混用。完美解决方案)

    上篇 IOS APP 国际化(实现不跟随系统语言,不用重启应用,代码切换stroyboard ,xib ,图片,其他资源 介绍了纯代码刷新 实现程序内切换语言. 但效率底下,也存在一些问题.暂放弃. ...

  3. Android 应用内切换语言

    extends :http://bbs.51cto.com/thread-1075165-1.html,http://www.cnblogs.com/loulijun/p/3164746.html 1 ...

  4. iOS开发--应用国际化,应用内切换语言

    1.前言 自己负责的项目需要做国际化,并且要求应用内部切换语言.这个是可以做到的,也并不难,可以直接戳Github看一下 https://github.com/leo90821/Localiztion ...

  5. iOS APP语言国际化之应用内切换语言环境

    最近接了一个项目,需求是要做一款应用的英文版本,客户并不清楚,以为要另做一个APP.沟通后告诉他们在之前应用基础上加个国际化功能就好,把之前的语言国际化重新梳理记录一下. 一般设置更改本地语言环境后, ...

  6. android 多语言(在APP里面内切换语言)

    创建SharedPreferences的管理类 public class PreferenceUtil { private static SharedPreferences mSharedPrefer ...

  7. iOS多语言(国际化)开发(尾随系统 + APP内手动设置)

    一:尾随系统切换语言 1>创建好项目project后, 新建一个多语言文件: 2>加入要设置的语言类型: 3>加入成功 细心的朋友可能会发如今English后面写的是3 Files ...

  8. iOS开发——iOS国际化 APP内语言切换

    最近一个一直在迭代的老项目收到一份新的开发需求,项目需要做国际化适配,简体中文+英文.由于项目中采用了storyboard和纯代码两种布局方式,所以国际化也要同时实现.上网查了些资料,实现了更改系统语 ...

  9. Android应用内部实现多语言,一键切换语言,国际化适配

    1.首先提供多语言对应的string值 如en对应英语, fr对应法语 两个文件中包含同样的key, 对应不同的语言的value 2.java代码相应用户切换语言动作 private static v ...

随机推荐

  1. 【js】基本类型和引用类型的区别

    1.保存方式:(一脸懵逼???) 基本类型是按值访问的,可以在变量的生命周期改变它,但是它是储存在哪里的呢?在浏览器缓存吗?[执行环境中定义的所有变量和函数都存储在执行环境的变量对象里,变量对象我们编 ...

  2. Visual Studio 2017 ASP.NET Core开发

    Visual Studio 2017 ASP.NET Core开发,Visual Studio 2017 已经内置ASP.NET Core 开发工具. 在选择.NET Core 功能安装以后就可以进行 ...

  3. vue入门 vue与react和Angular的关系和区别

    一.为什么学习vue.js vue.js兼具angular.js和react的优点,并且剔除了他们的缺点 官网:http://cn.vuejs.org/ 手册:http://cn.vuejs.org/ ...

  4. 浅谈HTML5中的浮动问题

    浮动是我们在前端页面中经常会用到的一种布局方式.那什么是浮动呢? 首先我们先来看一下它的定义.浮动是指让元素脱离文档标准流(脱标),按照指定的方向去横向排列.浮动的取值有两个,分别是float:lef ...

  5. hibernate从数据库中自动生成

    计应134(实验班) 李佳鸿 DB Brower配置 1.依次选择window-Open Perspective-MyEclipse Explorer

  6. dfs 无向图两节点间的所有路径

    标题:风险度量 X星系的的防卫体系包含 n 个空间站.这 n 个空间站间有 m 条通信链路,构成通信网.两个空间站间可能直接通信,也可能通过其它空间站中转. 对于两个站点x和y (x != y), 如 ...

  7. 如何用photoshop把一张图片分割成几张图片呢?

    今天情人节,祝大家节日快乐!朋友发来一张照片,我发现这张照片是几张照片组合起来的,是不是感觉每一张都是萌萌哒呢?为了体现单张的独特性,现在我要把它切分成单张,使用Photoshop CS5该怎么弄呢? ...

  8. React Native 之 数据持久化

    前言 因为 实战项目系列 涉及到数据持久化,这边就来补充一下. 如本文有错或理解偏差欢迎联系我,会尽快改正更新! 如有什么问题,也可直接通过邮箱 277511806@qq.com 联系我. demo链 ...

  9. 什么是https

    我们都知道HTTPS能够加密信息,以免敏感信息被第三方获取.所以很多银行网站或电子邮箱等等安全级别较高的服务都会采用HTTPS协议. HTTPS简介 HTTPS其实是有两部分组成:HTTP + SSL ...

  10. jmeter分布式压测

    stop.sh需要跑Jmeter的服务器上安装Jmeteryum install lrzsz 安装rz.sz命令rz jemter的压缩包 拷贝到/usr/local/tools下面unzip apa ...