Custom attributes in styles.xml Custom attributes in styles.xml android android

Custom attributes in styles.xml


I figured it out! The answer is to NOT specify the namespace in the style.

<?xml version="1.0" encoding="utf-8" ?><resources xmlns:android="http://schemas.android.com/apk/res/android">    <style name="CustomStyle">        <item name="android:layout_width">wrap_content</item>        <item name="android:layout_height">wrap_content</item>        <item name="custom_attr">value</item> <!-- tee hee -->    </style></resources>


above answer is worked for me, I tried a litte change, I declare styleable for a class in resources element.

<declare-styleable name="VerticalView">    <attr name="textSize" format="dimension" />    <attr name="textColor" format="color" />    <attr name="textBold" format="boolean" /></declare-styleable>

in declare-styleable, the name attribute referenced a class name, so I had a view class call "com.my.package.name.VerticalView", it represented this declare must be use in VerticalView or subclasses of VerticalView. so we can declare style like this :

<resources>    <style name="verticalViewStyle">        <item name="android:layout_width">match_parent</item>        <item name="android:layout_height">36dip</item>        <item name="textSize">28sp</item>  <!-- not namespace prefix -->        <item name="textColor">#ff666666</item>        <item name="textBold">true</item>    </style></resources>

that's why we didn't declare namespace at resources element, it still work.


values/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">    ...    <item name="defaultButtonColor">@color/red</item>    <item name="defaultButtonHeight">@dimen/dp_100</item></style>

values/attrs.xml

<resources>    <attr name="defaultButtonColor" format="reference" />    <attr name="defaultButtonHeight" format="reference"/></resources>

values/colors.xml

<resources>    <color name="red">#f00</color></resources>

values/dimens.xml

<resources>    <dimen name="dp_100">100dp</dimen></resources>

Using

<Button    android:layout_width="wrap_content"    android:layout_height="?attr/defaultButtonHeight"    android:text="Button"    android:textColor="?attr/defaultButtonColor"    />

enter image description here

DEMO