运行时多语言安卓应用? [英] Multi language android app during Runtime?
问题描述
我的目标是在运行时将应用程序语言从英文更改为中文,有什么建议吗?
My aim is to change an application language from English to Chinese during runtime, is there any suggestions?
language_spinner = (Spinner)findViewById(R.id.settings_language_spinner);
language_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (pos == 1){
Toast.makeText(parent.getContext(),"You have selected English",Toast.LENGTH_SHORT).show();
setLocale("en");
}else if (pos == 2){
Toast.makeText(parent.getContext(),"You have selected Chinese",Toast.LENGTH_SHORT).show();
setLocale("zh");
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (!conf.locale.getLanguage().equals(lang)) {
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, SettingsActivity.class);
startActivity(refresh);
finish();
}
}
此代码在英文下可以正常工作,但不能在中文下工作请帮助我找到解决方案..
This code is working properly with English but not working with Chinese please help me in finding the solution ..
推荐答案
我可以告诉你如何实现这个:
I can give you idea how you can implement this:
第一步:将values目录下所有文本的字符串文件制作成string-ch
,ch为中文代码.并在代码中使用 getResources.getString(R.string.text_name);
获取每个字符串,以便它可以在运行时获取英文或中文字符串值.
step 1: make string file for all texts in values directory as string-ch
, ch is the code for Chinese language. and in code get every string with the getResources.getString(R.string.text_name);
so that it can take string value at run time either English or Chinese.
第 2 步: 现在创建方法:
void changeLanguage(String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
第 3 步:在您想更改语言的地方调用此方法假设如果您想根据设备语言更改应用程序的语言,那么您可以调用如下:
step 3: call this method where you want to change language suppose if you want to get changed language of you application according to device language then you can call as:
changeLanguage(Locale.getDefault().getLanguage());
这篇关于运行时多语言安卓应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!