应用程式android内的语言切换 [英] Language switching inside app android
问题描述
如何在无需在Android应用程序内手动设置语言环境的情况下实现语言切换?我知道该应用程序将在启动过程中根据语言环境加载strings.xml,但我不希望基于系统语言环境做出此选择,而是希望在设置"中由用户指定.
How do I implement language switching without having to manually set locale inside an Android app? I know the app will load the strings.xml according to locale during startup, but I don't want this choice to be made based on system locale, but instead to be user-specified in Settings.
或者,手动设置区域设置是否正常?
Or, is manually setting locale fine?
推荐答案
您可以扩展Application类(也必须在清单中声明它),并在其中添加类似的内容.
You can extend Application class (you have to declare it in the manifest as well) and put something like this in it.
只要您想更改语言,就可以致电
Whenever you want to change language you can then call
((App)getApplicationContext()).changeLang(lang);
在您的活动中
. R.string.locale_lang只是存储在strings.xml中用于共享首选项的键
from within your activity. R.string.locale_lang is just a key which is stored in strings.xml for shared preferences
public class App extends Application {
private Locale locale = null;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (locale != null) {
Locale.setDefault(locale);
Configuration config = new Configuration(newConfig);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
}
@Override
public void onCreate() {
super.onCreate();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String lang = settings.getString(getString(R.string.locale_lang), "");
changeLang(lang);
}
public void changeLang(String lang) {
Configuration config = getBaseContext().getResources().getConfiguration();
if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {
Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
ed.putString(getString(R.string.locale_lang), lang);
ed.commit();
locale = new Locale(lang);
Locale.setDefault(locale);
Configuration conf = new Configuration(config);
conf.locale = locale;
getBaseContext().getResources().updateConfiguration(conf, getBaseContext().getResources().getDisplayMetrics());
}
}
public String getLang(){
return PreferenceManager.getDefaultSharedPreferences(this).getString(this.getString(R.string.locale_lang), "");
}
}
这篇关于应用程式android内的语言切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!