我想以编程方式找到我的所有应用程序。为此,我创建了所需的文件夹:
如果我更改了设备的语言,我的应用程序中的语言会发生变化。但我想选择语言。
为此,我创建了一个Preference活动。在本活动的最后,我写了这段代码:
...
mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
leng = value.toString();
int lengIndex = Integer.parseInt(leng) - 1;
// Update leguage summary
mPreferenceLeguage.setDefaultValue(lengIndex);
mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
if(leng.equals("1")){
saveLocale("en");
} else if(leng.equals("2")){
saveLocale("eu");
} else{
saveLocale("es");
}
return true;
}
});
}
public void saveLocale(String lang) {
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("CommonPrefs",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(langPref, lang);
editor.commit();
}
在MainActivity中,以下代码:
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
loadLocale();
...
public void loadLocale() {
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("CommonPrefs",
Activity.MODE_PRIVATE);
String language = prefs.getString(langPref, "");
changeLang(language);
}
public void changeLang(String lang) {
if (lang.equalsIgnoreCase(""))
return;
myLocale = new Locale(lang);
Locale.setDefault(myLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
config.locale = myLocale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
}
语言已更改,但不会立即更改。重新启动应用程序时语言会发生变化。
我希望这个chage会很简单。为此,我试图在saveLocale()metod结束时从Preference活动中重新调用MainActivity。
我能做些什么来解决它?
答案 0 :(得分:1)
/**Use below code Spinet it will work fine you need to recreate your
activity to change the language instantly without re-starting the app**/
Note: language ---> "en" or "eu" or "es". Based on your preference
private void updateLanguage(String language)
{
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
SharedPreferences languagepref = getSharedPreferences("language",MODE_PRIVATE);
SharedPreferences.Editor editor = languagepref.edit();
editor.putString("languageToLoad",language);
editor.apply();
recreate();
}
Override
public void recreate()
{
if (android.os.Build.VERSION.SDK_INT >= 14)
{
super.recreate();
}
else
{
startActivity(getIntent());
finish();
}
}
答案 1 :(得分:0)
要获取配置更改(例如区域设置更改),请确保您已在Android清单中注册了适当的配置更改:
https://developer.android.com/reference/android/R.attr.html#configChanges
您可以通过捕获onConfigurationChanged
中的更改来处理活动中的配置更改(在正确注册后)。
有关详细信息,请参阅Activity#onConfigurationChanged
文档:
https://developer.android.com/reference/android/app/Activity.html#onConfigurationChanged(android.content.res.Configuration)