应用程序内的语言切换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屋!