Creating default values for custom attributes using styles and themes

android, declare-styleable

Solution

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.

Problem

I have several custom `View`s 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> ```

Original source