【问题标题】:Wrong colorAccent when retrieving from theme从主题中检索时颜色重音错误
【发布时间】:2021-06-07 11:19:59
【问题描述】:

我想从应用程序主题中使用 colorAccent。有两个主题具有不同的强调色。我用这段代码实现它:

样式:

<style name="BaseAppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>

<style name="AppGreenTheme" parent="BaseAppTheme">
    <item name="colorAccent">@color/green</item>
</style>

<style name="AppRedTheme" parent="BaseAppTheme">
    <item name="colorAccent">@color/red</item>
</style>

布局:

<FrameLayout
    android:id="@+id/receives_funds_share"
    android:background="?colorAccent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

但它显示错误的颜色 (#04dac6)。当正确的颜色变深时(#05c0a5)。

当我将它从 android:background="?colorAccent" 更改为 android:background="@color/green" 时,它运行良好。有什么区别?如何从样式中正确检索accentColor?

在 Android 11 上测试。

【问题讨论】:

    标签: android material-design android-styles


    【解决方案1】:

    问题是,由于您使用Theme.MaterialComponents.Light.DarkActionBar 作为您的父母,colorAccent 不适用。请尝试将其替换为colorSecondary,如下所示。

    Theme.MaterialComponents 使用colorSecondary,并在他们的文档中如此描述。库中定义的所有组件都使用该属性。

    <style name="BaseAppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    </style>
    
    <style name="AppGreenTheme" parent="BaseAppTheme">
        <item name="colorSecondary">@color/green</item>
    </style>
    
    <style name="AppRedTheme" parent="BaseAppTheme">
        <item name="colorSecondary">@color/red</item>
    </style>
    

    【讨论】:

    • 不,它不起作用。我试图将视图的背景更改为 ?colorSecondary 并替换它的样式。但没有结果。
    • @BArtWell 好吧,这可能是一个很长的镜头,但你能检查一下是否没有像v21 或类似的样式的覆盖。我遇到过这种情况。
    • 是的,你是对的。我只是将它添加到 v27 样式中,现在它可以正常工作了。奇怪的是之前呈现出非常相似的颜色。谢谢!
    • @BArtWell 这确实令人气愤,但我以前也遇到过。所以你的v27 覆盖了你在这里所做的事情,因此它不起作用。好吧,很高兴现在解决了。
    【解决方案2】:

    您应该将主题设置为mainfest.xml中的活动:

    <activity
        android:name=".activities.MainActivity"
        android:theme="@style/AppGreenTheme">
    </activity>
    

    【讨论】:

    • 是的。我还尝试以编程方式设置主题并将其设置为 Application 和 Activity 标记。但是没有成功,颜色还是不对。
    猜你喜欢
    • 2019-08-23
    • 2011-07-12
    • 2015-07-07
    • 2012-06-12
    • 2022-11-13
    • 2015-07-06
    • 1970-01-01
    • 2013-09-09
    • 2013-03-11
    相关资源
    最近更新 更多