6

I have my theme defined as

<style name="AppThemeRed" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimaryRed</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDarkRed</item>
        <item name="colorAccent">@color/colorAccentRed</item>
    </style>

In my XML layouts, I am doing

<android.support.design.widget.AppBarLayout
        android:background="?attr/colorPrimary"
        android:id="@+id/topBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

Whenever I change any theme the colorPrimary changes

However, if I have the same thing added in drawable e.g

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="?attr/colorPrimary" />
            <corners android:radius="5dp"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="?attr/colorPrimary" />
            <corners android:radius="5dp"/>
        </shape>
    </item>
</selector>

It crashes with unable to inflate view, the view which has background set as @drawabe/xxxx

How can I define theme color attribute in my XML drawable

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Muhammad Umar
  • 11,391
  • 21
  • 91
  • 193

4 Answers4

4

just replace...

android:color="?attr/colorPrimary"

to...

android:color="@color/colorPrimaryRed"

Update

It is not possible to reference an attribute in an xml drawable below API 21. In order to make your theme you need to:

Create one xml drawable per theme. Include the needed color into you drawable directly with the @color tag or #RGB format.

Make an attribute for your drawable in attrs.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Attributes must be lowercase as we want to use them for drawables -->
    <attr name="my_drawable" format="reference" />
</resources>

Add your drawable to your theme.xml.

<style name="MyTheme" parent="@android:style/Theme.NoTitleBar">
   <item name="my_drawable">@drawable/my_drawable</item>
</style>

Reference your drawable in your layout using your attribute.

<TextView android:background="?my_drawable" />
Abhishek Singh
  • 9,008
  • 5
  • 28
  • 53
0

This seems to be supported on API 21+. Below that you cannot reference an attribute in drawable. https://code.google.com/p/android/issues/detail?id=26251.

This might help for workarounds: How to reference style attributes from a drawable?

Community
  • 1
  • 1
Amey Shirke
  • 599
  • 1
  • 5
  • 16
0

Can you please try

<solid android:color="@android:attr/colorPrimary"/>

instead of

<solid android:color="?attr/colorPrimary" />
Mahesh
  • 974
  • 6
  • 12
0

You can use :-

<solid android:color="@android:color/holo_orange_dark"  />
Nainal
  • 1,728
  • 14
  • 27