How to reference a color attribute in a style
I want to use the same drawable (having different colors) as the background for all buttons in the same layout.
extract / 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>
The above code will draw a horizontal line with storke = 4px width if I directly override the strokeColor
[ android:strokeColor="#ffff0000"
] value
But upon request, the background can have different colors. This is why I added ?attr/testColor
and want to define it with style.
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>
What works:
If I uncommented testColor
in AppTheme
, then all buttons have a blue line as their background.
What doesn't work:
If I use two different styles that have different colors (MyButton.Green, MyButton.Red), applying it to the Button, all I get is a transparent background.
source to share