如何保存用户的区域设置(在应用程序中)?

时间:2013-09-01 21:10:20

标签: java android eclipse sharedpreferences

我正在制作一款有两种可用语言的应用。用户通过单击按钮在语言之间切换。这是我的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);
}

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

1 个答案:

答案 0 :(得分: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);
相关问题