waynesford
waynesford

Reputation: 1698

How is the defStyleAttrs parameter used in obtainStyledAttributes

I am trying to create a custom compound view (subclassed out of relativelayout) on android and am trying to specify default styles. I can accomplish this, but I want to know what the defStyleAttr parameter is used for, and how to use it.

I have run into this method context.obtainStyledAttributes (AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes).

I understand that:

However, I can't figure out how to use int defStyleAttr parameter. I've read the documentation and have provided an attr resource like this:

<declare-styleable name="BMTheme">
        <attr name="BMButtonStyle" format="reference" />
</declare-styleable>

and then in my themes resource file I have this:

<style name="Theme.Custom" parent="@android:style/Theme">
    <item name="BMButtonStyle">@style/BMButton</item>
</style>

which in turn references this style:

<style name="BMButton">
    <item name="text">some string</item>
    <item name="android:paddingLeft">10dp</item>
    <item name="android:paddingRight">10dp</item>
</style>

In code, when I pass in 0 for defStyleAttr and the style resource id for defStyleRes, I successfully get the default values that I defined in my BMButton style:

TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RightArrowButton, 0, R.style.BMButton); 

However when I pass in the attr resource id for BMButtonStyle(which in turn references the BMButton style) for defStyleAttr, and 0 for defStyleRes then I do not get the values I specified in the style.

TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RightArrowButton, R.attr.BMButtonStyle, 0); 

Please let me know if I am using the defStyleAttr parameter the wrong way, and if anyone knows, why is there a need for both a defStyleAttr and a defStyleRes parameter when it seems like just a defStyleRes will suffice?

Upvotes: 6

Views: 6259

Answers (1)

waynesford
waynesford

Reputation: 1698

I figured out where I was going wrong after reading this post: Creating default style with custom attributes

Basically, in order to use the defStyleAttr parameter, my project needed to set my custom theme defined theme in the manifest.

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

Upvotes: 5

Related Questions