上下文/覆盖主题颜色

mar*_*o16 5 android colors android-theme android-styles android-attributes

我正面临一个问题,我尝试了几种方法来面对它,但仍然不成功.

我的应用程序使用多个主题,如:万圣节,圣诞节等,我正在使用TabLayout背景,文本颜色等小部件上的一些颜色属性来上传应用程序.

问题是:如何根据主题上下文使用具有不同值的相同颜色属性?

所以,基本上这是声明颜色的常规方法:

<color name="mapMarkerSelectedTextColor">@android:color/white</color>
<color name="mapLoadingIndicatorColor">@color/white</color>
Run Code Online (Sandbox Code Playgroud)

但是,主题和颜色是不可变的,所以我想,也许我可以覆盖每个主题内的那些颜色,如:

    <item name="mapMarkerUnselectedTextColor">@color/christmas_red</item>
    <item name="mapMarkerSelectedTextColor">@color/white</item>
Run Code Online (Sandbox Code Playgroud)

=>不成功

其他线索,将这些颜色声明为属性:

<attr name="mapLoadingIndicatorColor" format="reference|color" />
<attr name="map_autocomplete_accent_color" format="reference|color" />
Run Code Online (Sandbox Code Playgroud)

并在我的XML中使用主题:" ?attr/mapLoadingIndicatorColor".但是这个功能只允许自Lollipop版本以来导致崩溃.

我已经阅读了很多关于主题定制,颜色覆盖,但从未找到关于这种情况的明确解决方案.

不管怎么说,还是要谢谢你.

kar*_*sky 1

你提到:

并在我的 XML 中使用主题,如下所示:“?attr/mapLoadingIndicatorColor”。但此功能仅从 Lollipop 版本开始允许,并且之前会导致崩溃。

我不确定它?attr/something不能在 Lollipop 之前使用(Lollipop 的 API 级别为 21),因为我在模拟器中的 API 级别为 16 的设备上使用它并且工作正常。当选择不同的主题时,我用它来更改按钮的背景颜色,如下所示:

在activity_main.xml中(在布局文件夹中):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A button"
        style="?attr/myButton"/>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在 attrs.xml 中(在值文件夹中):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="myButton" format="reference"></attr>
</resources>
Run Code Online (Sandbox Code Playgroud)

在 styles.xml 中(在值文件夹中):

<resources>

<!-- default theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="myButton">@style/defaultButtonStyle</item>
</style>

<style name="defaultButtonStyle" parent="android:Widget.Button">
    <item name="android:background">@color/green</item>
</style>

<!-- custom theme -->
<style name="AppTheme.CustomTheme">
    <item name="myButton">@style/customButtonStyle</item>
</style>

<style name="customButtonStyle" parent="android:Widget.Button">
    <item name="android:background">@color/blue</item>
</style>

</resources>
Run Code Online (Sandbox Code Playgroud)

实际上,我对Android编程还很陌生,如果你能指定?attr/mapLoadingIndicatorColor在Lollipop之前在哪里找到导致崩溃的语句,那就太好了!(我在任何地方都找不到它,我只知道你不能使用棒棒糖前的提升属性)