【问题标题】:How to reference a color attribute in a style如何在样式中引用颜色属性
【发布时间】:2015-07-23 09:09:07
【问题描述】:

我想使用相同的可绘制对象(具有不同的颜色)作为一个布局中所有按钮的背景。

drawable/my_vector.xml

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="60px"
    android:width="360px"
    android:viewportHeight="60"
    android:viewportWidth="360" >

    <path
        android:name="bottom"
        android:pathData="M 0,60 L 360,60"
        android:strokeColor="?attr/testColor"
        android:strokeWidth="4" />

</vector>

如果我直接替换 strokeColor 值 [android:strokeColor="#ffff0000"],上面的代码将绘制一条宽度为 4px 的水平线

但根据要求,背景可以有不同的颜色。这就是为什么我添加了?attr/testColor 并希望使用样式来定义它。

值/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <declare-styleable name="dummyStyle">
        <attr name="testColor" format="color|reference" />
    </declare-styleable>

</resources>

值/样式.xml

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">

        <!-- <item name="testColor">#ff0000ff</item> -->

    </style>

    <style name="MyButton" parent="android:Widget.DeviceDefault.Button">
        <item name="android:background">@drawable/my_vector</item>
    </style>

    <style name="MyButton.Green">
        <item name="testColor">#ff00ff00</item>
    </style>

    <style name="MyButton.Red">
        <item name="testColor">#ffff0000</item>
    </style>
</resources>

layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <Button
        android:layout_marginTop="10px"
        android:id="@+id/test01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/MyButton.Green"
        android:text="Test01" />

    <Button
        android:layout_marginTop="10px"
        android:id="@+id/test02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/MyButton.Red"
        android:text="Test02" />

</LinearLayout>

什么有效:
如果我在AppTheme 中取消注释testColor,那么所有按钮都有蓝色线条作为背景。

什么不起作用:
如果我通过在 Button 上应用 2 种具有不同颜色的不同样式(MyButton.Green、MyButton.Red),我得到的只是透明背景。

【问题讨论】:

    标签: android android-layout themes android-xml


    【解决方案1】:

    尝试明确引用您的父样式parent="MyButton"

    【讨论】:

    • 添加一些解释,说明此答案如何帮助 OP 解决当前问题
    猜你喜欢
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2013-01-02
    • 2022-06-24
    • 2014-01-30
    • 1970-01-01
    • 2019-03-02
    相关资源
    最近更新 更多