使用SharedPreferences更改启动活动中的应用程序语言?
问题描述:
我用下面的代码来改变语言:使用SharedPreferences更改启动活动中的应用程序语言?
public void setLocale(String languageToLoad){
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
我的问题是,当我尝试加载“区域设置”使用SharedPreferences它似乎是陷阱在一个循环中,因为清爽的活动。所以我怎样才能加载最后的定位在开始活动。 在此先感谢。
答
我找到了答案:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//some code here
if (last_local.equals("fa") && current_local.equals("en"))
setLocale("fa");
//some code here
}
public void setLocale(String languageToLoad){
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
SharedPreferences Settings=getSharedPreferences("Last Setting",1);
Settings.edit().putString("Locale Status", languageToLoad).commit();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
我的问题是,我保存loace的onStop()方法,它是循环的原因。
答
您不需要再次启动活动。您只需通过调用setContentView()来重新创建视图和布局。
调用setLocale的代码在哪里? –
您可以比较用设置的区域设置设置的区域设置吗?如果他们是一样的,什么都不做? –