Let's say I have a simple form that draws a ring as follows:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:dither="true" android:innerRadiusRatio="3" android:shape="ring" android:thicknessRatio="36" android:useLevel="false" > <gradient android:centerColor="@android:color/holo_blue_bright" android:centerY="0.001" android:endColor="@android:color/holo_blue_dark" android:gradientRadius="202.5" android:startColor="@android:color/transparent" android:type="radial" android:useLevel="false" /> </shape>
And I apply this form as the background of the view as follows:
<View android:layout_width="96dp" android:layout_height="96dp" android:padding="16dp" android:background="@drawable/custom_shape" />
The exact details of the form are not relevant for this question - suffice it to say that I have a form. Now I do not want to hard code the various parameters for the form. Take thicknessRatio as an example. If I wanted the thickness coefficient to vary depending on the screen configuration, I would of course use the whole resource as follows. I will have value.xml with the following:
<item name="thickness_ratio" type="integer" format="integer">56</item>
And then, android:thicknessRatio="@integer/thickness_ratio" .
So far so good. Now I also want to have two โflavorsโ of my figure - โbigโ and โsmallโ, and I want to request a ratio of thickness that depends not on the configuration, but on the style applied to the presentation . What are the styles and themes for? So here is what I tried:
Step 1: Declare the attribute for the thickness ratio (attrs.xml):
<resources> <attr name="thicknessRatio" format="reference" /> </resources>
Step 2. Declare two styles using this attribute (styles, xml):
<style name="CustomShapeSmall"> <item name="thicknessRatio">@integer/thickness_ratio_small</item> </style> <style name="CustomShapeLarge"> <item name="thicknessRatio">@integer/thickness_ratio_large</item> </style>
Step 3: Define two integers in values.xml:
<item name="thickness_ratio_small" type="integer" format="integer">32</item> <item name="thickness_ratio_large" type="integer" format="integer">56</item>
Step 4: Request a custom attribute in a Drawable figure:
android:thicknessRatio="?attr/thicknessRatio"
Step 5: Apply the desired style to the View :
<View android:layout_width="96dp" android:layout_height="96dp" android:padding="16dp" style="@style/CustomShapeSmall" android:background="@drawable/custom_shape" />
Unfortunately this does not work. I get the following exception:
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/custom_shape.xml from drawable resource ID
From the exception stack trace, it seems that the line android:thicknessRatio="?attr/thicknessRatio" resolves the question mark followed by the integer value R.attr.thicknessRatio , however, no further resolution is performed to actually query the value of this attribute.
What am I missing here?
EDIT:
Here is the complete github project for this issue.