App内切换语言详解

前几天客户提需求,对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内切换语言

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!

时间: 2024-08-03 17:08:42

App内切换语言详解的相关文章

ASP内置对象详解之Application对象

application|对象|内置对象|详解 Application对象是个应用程序级的对象,用来在所有用户间共享信息,并可以在Web应用程序运行期间持久地保持数据. Application的属性: 方法如下: Application对象没有内置的属性,但是我们可以自行创建其属性. <% Application("属性名")=值 %> 其实大部分Application变量都 存放在Contents集合中,当你创建一个新的Application变量时,其实就是在Content

ASP内置对象详解之ObjectContext对象

object|对象|内置对象|详解 该对象用于控制Active Server Pages的事务处理.事务处理由Microsoft Transaction Server (MTS)管理. 事件 ObjectContext.OnTransactionAbort 由放弃的事务处理事件激发,在脚本完成处理后发生. ObjectContext.OnTransactionCommit 由成功的事务处理事件激发,在脚本完成处理后发生. 方法 ObjectContext.SetAbort 显式的放弃一次事务处理

ASP内置对象详解之Request对象

request|对象|内置对象|详解 Request对象用于接受所有从浏览器发往你的服务器的请求内的所有信息. 集合 Request.ClientCertificate(key[SubField]) 所有客户证书的信息的集合.对于Key,该集合具有如下的关键字: Subject 证书的主题.包含所有关于证书收据的信息.能和所有的子域后缀一起使用. Issuer 证书的发行人.包含所有关于证书验证的信息.除了CN外,能和所有的子域后缀一起使用. VadidFrom 证书发行的日期.使用VBScri

ASP内置对象详解之Response对象

response|对象|内置对象|详解 Response对象用于向客户端浏览器发送数据,用户可以使用该对象将服务器的数据以HTML的格式发送到用户端的浏览器,它与Request组成了一对接收.发送数据的对象,这也是实现动态的基础.下面介绍它常用的属性和方法. 1.Buffer属性 该属性用于指定页面输出时是否要用到缓冲区,默认值为False.当它为True时,直到整个Active Server Page执行结束后才会将结果输出到浏览器上.如:<%Response.Buffer=True%>&l

ASP内置对象详解之Server对象

server|对象|内置对象|详解 Server对象是ASP中一个很重要的对象,许多高级功能都是靠它来完成的.它提供了对Active Server Pages对和方法的使用,在这我主要介绍几个常用的方法. 1.MapPath方法 该方法返回指定文件的相对路径或物理路径.若Path以一个(/)或(\)开始,则MapPath方法返回路径时将Path视为完整的虚拟路径.若Path不是以斜杠开始,则MapPath方法返回同.asp文件中已有的路径相对的路径.如:test.asp文件位于C:\inetpu

ASP内置对象详解之Session对象

session|对象|内置对象|详解 Session其实指的就是访问者从到达某个特定主页到离开为止的那段时间.每一访问者都会单独获得一个Session.在Web应用程序中,当一个用户访问该应用时,Session类型的变量可以供这个用户在该Web应用的所有页面中共享数据:如果另一个用户也同时访问该Web应用,他也拥有自己的Session变量,但两个用户之间无法通过Session变量共享信息,而Application类型的变更则可以实现站点多个用户之间在所有页面中共享信息. 1.SessionID属

ASP内置对象详解精彩教程

对象|教程|内置对象|详解 使用ASP开发动态网站我们经常使用到其中的六个内置的对象,今天给大家收集了一下供大家参考! 1.ASP内置对象详解之Session对象 [2005-03-16]     2.ASP内置对象详解之Server对象 [2005-03-16]     3.ASP内置对象详解之Response对象 [2005-03-16]     4.ASP内置对象详解之Request对象 [2005-03-16]     5.ASP内置对象详解之ObjectContext对象 [2005-

string-android应用内切换语言,应用名称切换不过来

问题描述 android应用内切换语言,应用名称切换不过来 用了这个帖子中的方法http://my.oschina.net/jack1900/blog/290694?fromerr=HxWtLuYb 点击button后发现除了应用名称以外,其他的字符都改过来了 在我的manifest里面label的属性这样写的: 中英文的string我也都改过来了,不知道为什么还是改不过来 解决方案 http://jingyan.baidu.com/article/2fb0ba40b7893600f2ec5f9

nginx 内置变量详解及隔离进行简单的拦截_nginx

1,nginx内置变量 nginx 有很多内置变量可以进行简单的过滤. $arg_name 请求行中的name参数. $args 请求行中参数字符串. $cookie_name 名为name的cookie. 与$uri相同. $http_name 任意请求头的值:变量名的后半部为转化为小写并且用下划线替代横线后的请求头名称. $host "Host"请求头的值,如果没有该请求头,则为与请求对应的虚拟主机的首要主机名. $query_string 与$args相同. $realpath_