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

How to override configuration in Android application?

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

在我的 activity 中,我需要阅读首选项然后覆盖配置。在构造函数中上下文尚未准备好:

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

onCreate 中为时已晚:

java.lang.IllegalStateException: getResources() has already been called

引自 ContextThemeWrapper documentation:

This [applyOverrideConfiguration] method can only be called once, and must be called before any calls to getResources() or getAssets() are made.

覆盖配置的正确时间和地点是什么?

代码摘录自下面我当前的有效解决方案。

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());
}

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

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

升级到 appcompat 1.2.0 解决了 java.lang.IllegalStateException 的问题:getResources() 已被调用。 将 appcompat 依赖应用程序级别 build.gradle 替换为此

dependencies {
   implementation 'androidx.appcompat:appcompat:1.2.0'
}