How is the defStyleAttrs parameter used in obtainStyledAttributes

android, android-custom-view

Solution

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" >

Problem

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: - `AttributeSet set` I will get from the view's constructor if inflating from XML, - `int[] attrs` will be the key values for any custom view fields I may have created, - `int defStyleRes` will be a default style that I can provide, which is defined as a style resource. 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?

Original source