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

4

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

在我的活动中,我需要读取偏好设置并覆盖配置。但是在构造函数中,上下文还没有准备好:

尝试调用空对象引用上的'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());
}
2个回答

9

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

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

1
谢谢!这个解决方案帮助我解决了一个问题,即在实现Dagger Hilt后,Android 7及以下版本中更改语言无法正常工作。 - Aba

-1

升级到 appcompat 1.2.0 版本可以解决 java.lang.IllegalStateException: getResources() 已被调用的问题。 在 app 级别的 build.gradle 文件中,将 appcompat 依赖替换为以下内容

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接