getTheme().applyStyle(...) 多次而不覆盖前一个

Tho*_*Vos 2 android android-xml android-theme android-activity android-styles

当我多次将额外的属性应用到 AppTheme 时,它​​会覆盖前一个属性。这是我正在使用的代码:

主要活动:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {

    getTheme().applyStyle(R.style.AppTheme_OverlayPrimaryRed);

    // If you change `false` to `true`, the overlay above is overwritten.
    if (false) {
        getTheme().applyStyle(R.style.AppTheme_OverlayAccentRed);
    }

    super.onCreate(savedInstanceState);

    ...
}
Run Code Online (Sandbox Code Playgroud)

AppTheme.OverlayPrimaryRed:

<style name="AppTheme.OverlayPrimaryRed">
    <item name="colorPrimary">@color/material_red_500</item>
    <item name="colorPrimaryDark">@color/material_red_700</item>
</style>
Run Code Online (Sandbox Code Playgroud)

AppTheme.OverlayAccentRed:

<style name="AppTheme.OverlayAccentRed">
    <item name="colorAccent">@color/material_red_A200</item>
</style>
Run Code Online (Sandbox Code Playgroud)

有什么想法可以解决这个问题吗?

dev*_*ole 5

您的样式定义AppTheme.OverlayPrimaryRedAppTheme.OverlayAccentRed隐式继承自AppTheme. 由于AppTheme可能还包含一个定义colorPrimarycolorPrimaryDark第二applyStyle声明,将这些属性以及,撤消第一个applyStyle电话。

出于这个原因,我在回答这个问题时没有在样式覆盖名称中使用任何点。

如果出于美学原因要保留点,则可以为叠加定义一个空的父样式,如下所示:

<style name="Overlay">
</style>

<style name="Overlay.PrimaryRed">
    <item name="colorPrimary">@color/material_red_500</item>
    <item name="colorPrimaryDark">@color/material_red_700</item>
</style>

<style name="Overlay.AccentRed">
    <item name="colorAccent">@color/material_red_A200</item>
</style>
Run Code Online (Sandbox Code Playgroud)