16

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>
happydude
  • 3,869
  • 2
  • 23
  • 41

1 Answers1

15

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.

happydude
  • 3,869
  • 2
  • 23
  • 41
  • 2
    More than that, if a second parameter for default value does not exist (like getString()) you can just check to see if its null and then specify the default value itself at runtime. – renatoaraujoc Mar 26 '15 at 18:15
  • How about allowing the user to choose from number of values [options with only acceptable values], shown as options as the user goes on typing the attribute. In Android default and known components, when you want to give in [ comes with other options that you can choose from] or in [ comes with other options that you can choose from] in a drop-down that emerges there. – Abhinav Saxena Jun 22 '18 at 11:35