gpt4 book ai didi

java - 屏幕旋转时保存语言

转载 作者:太空宇宙 更新时间:2023-11-04 13:04:51 25 4
gpt4 key购买 nike

我使用下面的方法通过将语言代码作为字符串传递来更改应用程序的语言。
当我更改屏幕方向时,语言将恢复为默认语言,并且所有 View 也会重置。

 public String setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, Login.class);
startActivity(refresh);
finish();
return lang;
}

我尝试使用onSaveInstanceStateonRestoreInstanceState ,但我不知道如何使所有这些方法一起工作。

最佳答案

使用共享首选项,您可以存储语言并在屏幕方向更改时获取存储的值。

public String setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, Login.class);
startActivity(refresh);
finish();
// save shared preference here or later, your choice.
return lang;
}

用于创建和保存共享首选项的代码。

SharedPreferences  preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor nameEditor = preferences.edit();
nameEditor.putString("saved_lang", lang);
nameEditor.commit();

用于检索共享首选项值的代码。

//To get language when screen changes.
String lang = preferences.getString("saved_lang", "");

您可以使用same principal to save other values and settings .

关于java - 屏幕旋转时保存语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34590830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com