[英]How to change language permanently on Android Studio?
我使用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);
}
}
将用户首选项保存为共享首选项。
/******* 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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.