0

我正在制作一个有两种可用语言的应用程序。用户通过单击按钮在语言之间切换。这是我的 onClick 方法:

public void setLocaleEng(View v){
    Locale localeEng = new Locale("en");
    Locale.setDefault(localeEng);
    Configuration configEng = new Configuration();
    configEng.locale = localeEng;
    getBaseContext().getResources().updateConfiguration(configEng, getBaseContext().getResources().getDisplayMetrics());
    Intent intent = new Intent(NastavitveJezika.this, MainActivity.class);
    finish();
    startActivity(intent);
}

public void setLocaleSlo(View v){
    Locale localeSlo = new Locale("sl");
    Locale.setDefault(localeSlo);
    Configuration configSlo = new Configuration();
    configSlo.locale = localeSlo;
    getBaseContext().getResources().updateConfiguration(configSlo, getBaseContext().getResources().getDisplayMetrics());
    Intent intent = new Intent(NastavitveJezika.this, MainActivity.class);
    finish();
    startActivity(intent);
}

这可以正常工作,但是当用户完全退出应用程序并重新打开它时,它将恢复为默认值(英语)。如何让我的应用记住用户选择的语言设置?如果答案是共享首选项,那该怎么做?到目前为止,我只使用共享首选项来存储字符串和布尔值,我不知道如何处理这样的事情。

4

1 回答 1

2

如果答案是共享首选项,那该怎么做?我只使用共享首选项来存储字符串。

是的,答案是 SharedPreferences,您可以像以前一样使用它来存储字符串。只需让它存储“en”或“sl”然后

    String enOrSlReadFromSharedPrefs = readSharedPrefsJustLikeYouDidBefore();
    Locale locale = new Locale(enOrSlReadFromSharedPrefs);
    Locale.setDefault(locale);
    Configuration configSlo = new Configuration();
    configSlo.locale = localeSlo;
    getBaseContext().getResources().updateConfiguration(configSlo, getBaseContext().getResources().getDisplayMetrics());
    Intent intent = new Intent(NastavitveJezika.this, MainActivity.class);
    finish();
    startActivity(intent);
于 2013-09-01T22:10:43.297 回答