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>

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 <android:inputType = "textPassword"> in <EditText> [<textPassword> comes with other options that you can choose from] or <android:scaleType = "fitCenter"> in <ImageView> [<centerinside> comes with other options that you can choose from] in a drop-down that emerges there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.