Allow usage of values like ‘wrap_content’ in attrs.xml

325 Views Asked by At

How can I allow usage of values like wrap_content or match_parent in attrs.xml resource file on Android?

My attrs.xml.

<declare-styleable name="BarView">
    <attr name="foo_dimen" format="dimension" />
</declare-styleable>

I want the foo_dimen attribute to be used like this:

<BarView
    …
    app:foo_dimen="wrap_content" />
<BarView
    …
    app:foo_dimen="42dp" />
1

There are 1 best solutions below

0
On

It can be done using <enum />:

<declare-styleable name="BarView">
    <attr name="foo_dimen" format="dimension">
        <enum name="wrap_content" value="-1" />
    </attr>
</declare-styleable>

Then you can get the value using Java:

TypedArray arr = context.getTheme().obtainStyledAttributes(R.styleable.BarView, /* defStyleAttr */ 0, /* defStyleRes */ 0);
switch ((int)(arr.getDimension(R.styleable.BarView_foo_dimen, -255))) {
    case -1: // wrap_content
        // …
        break;
    case -255: // not specified
        // …
        break;
    default: // Specified valid dimension
        int pixels = arr.getDimensionPixelSize(R.styleable.BarView_foo_dimen, -1);
        …
        break;
}