安卓内置语言切换
最近公司项目需要三种语言的实现,添加中英柬三国语言,不能跟随系统语言走,可以实现自行切换,所以开始研究下如何实现三种语言的切换。
首先你需要在你的资源文件下建立你需要的语言包
然后把你需要翻译的文字写在对应语言的xml文件中
中文
<string name="user_means">我的个人信息</string>
<string name="calear_img">清空图片缓存</string>
<string name="jiancha_gengxin">切换语言</string>
<string name="mianze">免责声明</string>
<string name="qiu_rent">求租</string>
<string name="qiu_buy">求售</string>
<string name="dai_shen">待审核</string>
<string name="dai_see">带看中</string>
<string name="yichengjiao">已成交</string>
英文
<string name="user_means">My personal information</string>
<string name="calear_img">Delete the Image</string>
<string name="jiancha_gengxin">Check for updates</string>
<string name="mianze">Disclaimer</string>
<string name="qiu_rent">Asking for rent</string>
<string name="qiu_buy">Asking for sale</string>
<string name="dai_shen">Waiting for approval</string>
<string name="dai_see">Follow up</string>
<string name="yichengjiao">Deal case</string>
柬文
<string name="user_means">ទិន្នន័យផ្ទាល់ខ្លួនរបស់ខ្ញុំ</string>
<string name="calear_img">លុបចោលរូបភាព</string>
<string name="jiancha_gengxin">ពិនិត្យមើលពត័មានថ្មីៗ</string>
<string name="mianze">ការបដិសេធ</string>
<string name="qiu_rent">ស្វែងរកការជួល</string>
<string name="qiu_buy">ស្វែងរកការលក់់</string>
<string name="dai_shen">រង់ចាំការពនិត្យសំរេច</string>
<string name="yichengjiao">case ដែលបានសំរេច</string>
然后在自己的activity中写如切换的dialog
new AlertDialog.Builder(this)
.setTitle("语言切换")
.setIcon(android.R.drawable.ic_dialog_info)
.setSingleChoiceItems(new String[] { "中文", "English","ភាសាខ្មែរ" }, 3,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
switch (which){
case 0 :
language = "ch";
break;
case 1 :
language = "en";
break;
case 2 :
language = "km";
break;
}
}
}).setNegativeButton("取消", null)
.setNeutralButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
SharePreUtils.newInstance(SettingActivity.this).updatlanguage(language);
showLanguage(language);
freshView();
}
}).show();
protected void showLanguage(String language) {
//设置应用语言类型
Resources resources = getResources();
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();
if (language.equals("ch")) {
config.locale = Locale.SIMPLIFIED_CHINESE;
} else if(language.equals("en")){
config.locale = Locale.ENGLISH;
}
else {
config.locale = new Locale("km");
}
resources.updateConfiguration(config, dm);
//保存设置语言的类型(这个里面我先保存一下,下面会讲到他的用处)
SharePreUtils.newInstance(this).updatlanguage(language);
//PreferenceUtil.commitString("language", language);
}
private void freshView(){
Intent intent = new Intent(this, SettingActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
所有代码都已经写出来了,大家可以自己自行编写。