I want to use same drawable (having different colors) as background for all the buttons in one layout.
drawable/my_vector.xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://ift.tt/nIICcg"
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>
Above code will draw a horizontal line having storke width = 4px if I directly substitute strokeColor value [android:strokeColor="#ffff0000"]
But as per requirement, background can have different colors. That is why I have added ?attr/testColor and want to define it using style.
values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://ift.tt/nIICcg">
<declare-styleable name="dummyStyle">
<attr name="testColor" format="color|reference" />
</declare-styleable>
</resources>
values/styles.xml
<resources xmlns:android="http://ift.tt/nIICcg"
<!-- 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://ift.tt/nIICcg" xmlns:tools="http://ift.tt/LrGmb4"
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 uncomment testColor in AppTheme, then all buttons have blue-color line as a background.
What does not work:
If I use 2 different styles having different colors (MyButton.Green, MyButton.Red) by applying it on Button, all I get is a transparent background.
Aucun commentaire:
Enregistrer un commentaire