App内切换语言详解
作者:tnnowu 发布时间:2023-04-12 11:21:44
标签: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内切换语言
来源:http://www.cnblogs.com/cnwutianhao/p/6746981.html
0
投稿
猜你喜欢
- 背景:用习惯了idea再去用eclipse实在用的不习惯,于是将老的eclipse项目导入到eclipse,网上有很多教程,看了很多博客都不
- 路由事件模型传统的简单事件模型中,在消息激发是将消息通过事件订阅的然后交给事件的相应者,事件的相应者使用事件的处理器来做出相应,这样就存在一
- 本文实例讲述了C#静态static的用法,分享给大家供大家参考。具体用法分析如下:一、静态类静态类与非静态类的重要区别在于静态类不能实例化,
- 问题背景实际项目碰到一个上游服务商接口有10秒的查询限制(同个账号)。项目中有一个需求是要实时统计一些数据,一个应用下可能有多个相同的账号。
- 使用Button时为了让用户有“按下”的效果,有两种实现方式:1.在代码里面。imageButton.setOnTouchListener(
- spring WEB MVC框架提供了一个MVC(model-view-controller)模型-视图-控制器的结构和组件,利用它可以开发
- 项目结构:效果图一:效果图二:效果图三:关于闹钟:Alarm hongten v1.0 使用说明: &nbs
- 一、JMeter后端 * 介绍说到JMeter后端 * ,必须要从源头BackendListener开始说,最后延伸到我们需要的Backen
- 前言废话不多说直接开始老规矩,文章最后有源码完成效果图棋子加渐变色棋子不加渐变色一、测量1.获取宽高 @Override protected
- 前言我们在很大的项目开发,会发现项目引用的 dll 会很多,我想要按照不同的功能,将不同的 dll 放在不同的文件夹简单的方法是通过修改 A
- 常用的Dialog有确认对话框,单选按钮对话框,多选按钮对话框,复选按钮对话框另外还有自定义的对话框AlertDialog的常用方法setT
- 本文实例为大家分享了C#实现图片切割、切图的具体代码,供大家参考,具体内容如下前台准备两个Image控件。上面是显示原图,下面显示切割后的效
- 前言工作中是否遇到这样的场景?1、需要异步线程执行,而且需要获取到线程执行返回的结果。2、如果执行过程异常,可以按照自定义方式消费异常信息。
- 创建一个类,在该类的主方法中创建标准输入流的扫描器对象,提示用户输入一个整数,并通过扫描器的方法来接受这个整数,然后通过三元运算符判断该数字
- 安装JDK/安装JRE以及配置java环境变量对于java初学者来说是一件比较头疼的事情,这边分享一个简单的批处理命令,助大家一步完成JDK
- java 避免出现NullPointerException(空指针)的方法总结Java应用中抛出的空指针异常是解决空指针的最好方式,也是写出
- Cocos2d-x从2.x版本到上周刚刚才发布的Cocos2d-x 3.0 Final版,其引擎驱动核心依旧是一个单线程的“死循环”,一旦某
- java synthetic关键字。有synthetic标记的field和method是class内部使用的,正常的源代码里不会出现synt
- 本文实例汇总了C#常用GDI+文字操作,包含了文字的投影、倒影、旋转等常见的效果,在进行C#应用程序开发中有不错的实用价值。分享给大家供大家
- 前言最近在用 MVP + RxJava + Retrofit 写项目,觉得相对于其他的开发框架,这的确是给我们带来了很多方便,但是在网上搜寻