Creating default values for custom attributes using styles and themes

happydude picture happydude · Jun 2, 2012 · Viewed 9.8k times · Source

I have several custom Views in which I have created custom styleable attributes that are declared in xml layout and read in during the view's constructor. My question is, if I do not give explicit values to all of the custom attributes when defining my layout in xml, how can I use styles and themes to have a default value that will be passed to my View's constructor?

For example:

attrs.xml:

<declare-styleable name="MyCustomView">
    <attr name="customAttribute" format="float" />
</declare-styleable>

layout.xml (android: tags eliminated for simplicity):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.mypackage" >

    <-- Custom attribute defined, get 0.2 passed to constructor -->

    <com.mypackage.MyCustomView
        app:customAttribute="0.2" />

    <-- Custom attribute not defined, get a default (say 0.4) passed to constructor -->

    <com.mypackage.MyCustomView />

</LinearLayout>

Answer

happydude picture happydude · Sep 28, 2012

After doing more research, I realized that default values can be set in the constructor for the View itself.

public class MyCustomView extends View {

    private float mCustomAttribute;

    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray array = context.obtainStyledAttributes(attrs,
            R.styleable.MyCustomView);
        mCustomAttribute = array.getFloat(R.styleable.MyCustomView_customAttribute,
            0.4f);

        array.recycle();
    }
}

The default value could also be loaded from an xml resource file, which could be varied based on screen size, screen orientation, SDK version, etc.