【问题标题】:Force theme change as observable action强制主题更改为可观察的动作
【发布时间】:2018-07-10 13:31:47
【问题描述】:

我正在尝试在 Android 中实现主题更改,因为由于某些异步操作,我需要动态更改整个应用程序的外观。

我有几个这样的主题:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
</style>

<style name="YellowTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorYellowLight</item>
        <item name="colorPrimaryDark">@color/colorYellowDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
</style>

<style name="GreenTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorGreenLight</item>
        <item name="colorPrimaryDark">@color/colorGreenDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
 </style> 

我正在使用MutableLiveData 来存储一些对象,用作主题更改的基础:

val dayTypeDTO = MutableLiveData<DayTypeDTO>()

然后我正在观察这个对象,当它的值发生变化时,我需要更改应用主题:

cache.dayTypeDTO.observe(this, Observer { dto ->
            if (dto != null) setTheme(dto.theme)
})

问题是主题更改应该在视图膨胀之后发生。否则,不适用。但是由于我在创建视图后注册观察者,并且由于无法预测的动态变化,我不能真正这样做。

我知道我可以调用activity.recreate(),但这只会导致无限循环。

有人可以建议如何实现此主题更改,以便所有使用 colorPrimary 的组件都因此可观察操作而更新?最好是手动一一更改。

【问题讨论】:

    标签: android kotlin rx-java2 android-theme


    【解决方案1】:

    在你的视图中添加一个 onGlobalLayoutListener 以确保布局在设置主题之前被膨胀:

    https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2015-07-13
      • 2019-03-14
      相关资源
      最近更新 更多