我使用Android Studio创建了一个Android应用,可以更改语言设置,同时从顶部菜单按钮执行它。一切正常,但每当我关闭应用程序或旋转屏幕时,语言都会重置为系统。如何在应用永久性内进行更改? (请注意,在 AndroidManifest.xml 中,我有以下行android:configChanges="locale"
并删除它并不能解决问题。)
我在 MainActivity.java 中使用了以下代码:
public void changeLanguage (String toLoad) {
Locale locale = new Locale(toLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale= locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String languageToLoad;
switch (item.getItemId()) {
case R.id.english_menu:
languageToLoad = "en";
changeLanguage(languageToLoad);
return true;
case R.id.italian_menu:
languageToLoad = "it";
changeLanguage(languageToLoad);
return true;
case R.id.french_menu:
languageToLoad = "fr";
changeLanguage(languageToLoad);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:2)
将用户首选项保存到共享首选项。
/******* Create SharedPreferences *******/
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
/**************** Storing data as KEY/VALUE pair *******************/
editor.putString("lang_code", "en"); // Saving string
// Save the changes in SharedPreferences
editor.commit(); // commit changes
创建应用程序类和此类的oncreate方法设置应用程序本地
public class BaseJuiceApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Locale locale = new Locale(pref.getString("lang_code","en"));
Locale.setDefault(locale);
Configuration conf = getBaseContext().getResources().getConfiguration();
config.locale= locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
}