Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating default style with custom attributes

So here's my problem: I've created a custom component which extends the Button This button has one attribute called testAttr.

<declare-styleable name="TestButton" parent="@android:style/Widget.Button">
    <attr name="testAttr" format="reference|color"/>
</declare-styleable>

I want to create a default style for this component so i added this:

<declare-styleable name="TestTheme">
    <attr name="testStyle" format="reference"/>
</declare-styleable>

<style name="Theme.AppTheme" parent="@android:style/Theme" >
    <item name="testStyle">@style/test</item>
</style>

The problem is that i want to use both android attributes and my own like this, which isn't working:

<style name="test" parent="@android:style/Widget.Button">
    <item name="android:background">#FF0000</item>
    <item name="testAttr">testText</item>
</style>

I set the default styles in my custom component as follows:

public myButton(final Context context) {
    this(context, null);
}

public myButton(final Context context, final AttributeSet attrs) {
    this(context, attrs, R.styleable.TestTheme_testStyle);
}

public myButton(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);

    final TypedArray array = context.obtainStyledAttributes(
            attrs,
            R.styleable.TestButton,
            defStyle,
            R.style.testDefault);
        final String s = array.getString(R.styleable.TestButton_testAttr);
        setText(s);
        array.recycle();
}

And of course i set the Theme in the manifest:

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppTheme" >

    <activity
        android:name=".TestActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


</application>

It always falls back to the default style for some reason and never sets the android attributes. So am i missing something here?

like image 794
Nick Avatar asked Aug 22 '12 11:08

Nick


1 Answers

Well, I should've looked better before asking questions...

found the solution:

replaced this:

public myButton(final Context context, final AttributeSet attrs) {
    this(context, attrs, R.styleable.TestTheme_testStyle);
}

with this:

public myButton(final Context context, final AttributeSet attrs) {
    this(context, attrs, R.attr.testStyle);
}
like image 72
Nick Avatar answered Sep 22 '22 21:09

Nick