本文介绍了多次getTheme().applyStyle(...),而不会覆盖前一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I apply extra attributes to the AppTheme multiple times it overwrites the previous one. This is the code I am using:

MainActivity:

@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);

    ...
}

AppTheme.OverlayPrimaryRed:

<style name="AppTheme.OverlayPrimaryRed">
    <item name="colorPrimary">@color/material_red_500</item>
    <item name="colorPrimaryDark">@color/material_red_700</item>
</style>

AppTheme.OverlayAccentRed:

<style name="AppTheme.OverlayAccentRed">
    <item name="colorAccent">@color/material_red_A200</item>
</style>

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

Any ideas how I can solve this issue?

推荐答案

您的样式定义AppTheme.OverlayPrimaryRedAppTheme.OverlayAccentRed隐式继承自AppTheme.由于AppTheme可能还包含colorPrimarycolorPrimaryDark的定义,因此第二个applyStyle语句也将设置这些属性,从而撤消第一个applyStyle调用.

Your style definitions AppTheme.OverlayPrimaryRed and AppTheme.OverlayAccentRed implicitly inherit from AppTheme. Since AppTheme probably also contains a definition for colorPrimary and colorPrimaryDark the second applyStyle statement will set these attributes as well, undoing the first applyStyle call.

由于这个原因,我在此问题的答案中没有在样式覆盖名称中使用任何点..

For this reason I did not use any dots in the style overlay names in my answer to this question.

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

If you want to keep the dots for esthetical reasons you can define an empty parent style for overlays like so:

<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>

这篇关于多次getTheme().applyStyle(...),而不会覆盖前一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 00:56