首页 > 解决方案 > Android:继承样式并在其中设置自定义属性的值不起作用

问题描述

我有一个自定义属性attr.xml

<resources>
    <attr name="buttonBackgroundColor" format="reference"/>
</resources>

我创建了一个button_background.xml使用该自定义属性的drawable:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="?buttonBackgroundColor"/>


    <corners android:radius="7dp" />
</shape>

我定义了如下风格:

<style name="button_background">
        <item name="android:background">@drawable/button_background</item>
        <item name="android:elevation">3dp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:paddingTop">15dp</item>
        <item name="android:paddingBottom">15dp</item>
        <item name="android:gravity">center</item>

    </style>

我在这些子样式中定义该自定义属性的值:

<style name="button_background_green" parent="button_background">
      <item name="buttonBackgroundColor">@color/Green</item>
</style>

<style name="button_background_blue" parent="button_background">
      <item name="buttonBackgroundColor">@color/Blue</item>
</style>

button_background_green在 a 中使用麦粒肿TextView

<TextView
    android:id="@+id/done"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    style="@style/button_background_green"
    android:textSize="17sp"
    android:text="@string/done" />

我认为这就是我们实现具有许多共同属性但不起作用的样式的方式。如果我将android:background属性设置为子样式的颜色,它会完美运行。所以我认为由于某种原因它无法读取buttonBackgroundColor属性。请帮忙。我真的很感激。

标签: androidandroid-layoutandroid-styles

解决方案


推荐阅读