已解决(解决方案在底部)
在我的活动中,我需要读取偏好设置并覆盖配置。但是在构造函数中,上下文还没有准备好:
尝试调用空对象引用上的'java.lang.String android.content.Context.getPackageName()'的虚拟方法
在onCreate
中太晚了:
java.lang.IllegalStateException:已经调用getResources()
ContextThemeWrapper 文档中的引用:
此[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());
}