如何在样式中引用颜色属性

3

我希望在同一个布局中为所有按钮使用相同的可拉伸矢量图形(具有不同的颜色)作为背景。

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>

上述代码将绘制一条水平线,其描边宽度为4像素,如果我直接替换 strokeColor 的值 [android:strokeColor="#ffff0000"]。
但是根据要求,背景可以有不同的颜色。这就是为什么我添加了 ?attr/testColor 并希望使用样式来定义它的原因。
values/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>

values/styles.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,那么所有的按钮都将有一个蓝色线作为背景。

无效方法:
如果我使用具有不同颜色(MyButton.Green,MyButton.Red)的不同样式,并将其应用于按钮,则所得到的仅是透明背景。

1个回答

0

尝试显式引用父样式 parent="MyButton"


为了帮助 OP 解决当前的问题,可以在答案中添加一些解释说明。 - ρяσѕρєя K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接