【问题标题】:How to override configuration in Android application?如何覆盖 Android 应用程序中的配置?
【发布时间】:2018-08-12 06:27:12
【问题描述】:

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

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

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

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

    【讨论】:

    • 谢谢!此解决方案帮助我解决了在实施 Dagger Hilt 后更改语言在 Android 7 及更低版本中无法正常工作的问题。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多