【发布时间】:2018-08-12 06:27:12
【问题描述】:
已解决(底部的解决方案)
在我的活动中,我需要阅读首选项,然后覆盖配置。在构造函数中 Context 还没有准备好:
尝试在空对象引用上调用虚拟方法“java.lang.String android.content.Context.getPackageName()”
在onCreate 为时已晚:
java.lang.IllegalStateException: getResources() 已经被调用
引用自 ContextThemeWrapper documentation:
此 [applyOverrideConfiguration] 方法只能调用一次,并且必须在调用 getResources() 或 getAssets() 之前调用。
什么是覆盖配置的正确时间和地点?
下面是我当前工作解决方案的代码摘录。
class OverrideActivity extends AppCompatActivity {
// ...
private boolean __overrideConf = false;
@Override
public Resources getResources() {
if (!__overrideConf) {
// ...
// read shared preferences needs context
// ...
applyOverrideConfiguration(configuration);
__overrideConf = true;
}
return super.getResources();
}
}
解决方案(覆盖受保护的方法attachBaseContext)
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
applyOverrideConfiguration(new Configuration());
}
【问题讨论】:
标签: android android-activity android-preferences activity-lifecycle