我一直想知道为什么我的onCreate方法运行两次,现在发现它与我在启动时设置应用的语言环境有关...我的问题是,是否有必要这样做是否运行两次?
这是使onCreate运行两次的代码:
/*Sets the language of the application and also returns the integer value of selected language*/
protected Integer setLanguage() {
String lang = prefs.getString("language-key","0");
Integer language = Integer.parseInt(lang);
Configuration config = context.getResources().getConfiguration();
if (!decideLang(language).equals("") && !config.locale.getLanguage().equals(decideLang(language))) {
setLocale(decideLang(language));
}
return language;
}
/*Sets the locale*/
private void setLocale(String lang) {
((Activity) context).recreate();
Locale myLocale = new Locale(lang);
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
setLanguage方法返回的整数稍后将用于确定稍后使用的URL,但是我意识到这对我的问题并不重要。
我的问题是,由于此代码,为什么onCreate需要运行两次?
答案 0 :(得分:0)
((Activity) context).recreate();
,就像在锡罐上所声明的那样,会重新创建Activity,因此onCreate()当然会被调用两次。
(来自comments)