如何覆盖Android应用程序中的配置?

Rus*_*nas 3 android android-preferences activity-lifecycle android-activity

已解决(底部的解决方案)

在我的活动中,我需要阅读首选项,然后覆盖配置。在构造函数中 Context 还没有准备好:

尝试在空对象引用上调用虚拟方法“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();
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方案(覆盖受保护的方法attachBaseContext

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(newBase);
    applyOverrideConfiguration(new Configuration());
}
Run Code Online (Sandbox Code Playgroud)

Rus*_*nas 7

解决方案(覆盖受保护的方法attachBaseContext

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(newBase);
    // copypaste safe code
    applyOverrideConfiguration(new Configuration());
}
Run Code Online (Sandbox Code Playgroud)