java - 屏幕旋转时保存语言

标签 java android android-orientation

我使用下面的方法通过将语言代码作为字符串传递来更改应用程序的语言。
当我更改屏幕方向时,语言将恢复为默认语言,并且所有 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/

相关文章:

android - MultiAutoCompleteTextView 添加 ", "

android - 使用支持库崩溃的 Proguard Android 应用程序

android:screenOrientation=”locked” 在旧操作系统版本上

java - 尝试读取进程输入流

java - 如何从来自 Google Maps API 的字符串中查找城市名称

java - 如何使用 postgis 和 hibernate-spatial 正确映射多边形类型?

android - 如何在 MVVM 架构中使用协程并进行改造

java - 如何将类的一个参数的值复制到另一个Collection对象?

android - 如何在 camera2 Android api 中创建一个 BottomBar 作为 StickyBottomCaptureLayout?

android - 检测方向变化,当 Android 只允许纵向时