Android : Injecting attributes into drawable resources files on Android

on Thursday, March 19, 2015


I'm trying to find the best way to reuse resource files. In this example, I'm trying to create a ghost button for Android. I have a ghost button drawable xml file that defines the background, but I would like to be able to specify the color (specifically without using theme based defined colors).


ghost.xml:



<shape
android:shape="rectangle">
<corners android:radius="@dimen/ghost_button_corner" />
<solid android:color="@android:color/transparent" />
<stroke android:width="@dimen/ghost_button_stroke_size" android:color="?attr/ghost_color" /></shape>


ghost_style.xml:



<!-- STYLABLE -->
<attr name="ghost_color" format="reference" />

<!-- STYLES -->
<style name="GhostButtonBlack" parent="@style/GhostButton">
<item name="ghost_color">@android:color/black</item>
</style>

<style name="GhostButtonWhite" parent="@style/GhostButton">
<item name="ghost_color">@android:color/white</item>
</style>

<!-- BASE -->
<style name="GhostButton" parent="android:style/Widget.Button">
<item name="android:textSize">@dimen/ghost_button_text_size</item>
<item name="android:textColor">?attr/ghost_color</item>
<item name="android:background">@drawable/ghost</item>
</style>


within layout.xml:



<Button
style="@style/GhostButtonWhite"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="5dp"
android:text="White Ghost Button" />


But I'm currently getting the following exception:



Caused by: java.lang.RuntimeException: Failed to resolve attribute at index 5
at android.content.res.TypedArray.getColorStateList(TypedArray.java:425)
at android.widget.TextView.<init>(TextView.java:987)

0 comments:

Post a Comment