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

问题描述 投票:0回答:1

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

在我的活动中,我需要阅读首选项,然后覆盖配置。在构造函数中,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
1个回答
1
投票

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

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(newBase);
    // copypaste safe code
    applyOverrideConfiguration(new Configuration());
}
© www.soinside.com 2019 - 2024. All rights reserved.