3

I create an attribute in attrs.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Custom">
        <attr name="src" format="integer" />
    </declare-styleable>
</resource>

And in my code, I get the value of the attribute like this: attrs.getAttributeIntValue("mynamespace", "src", -1);

It works. I get the value of 'src' from the layout xml file. But my question is why android does not generate a value in R class so that I don't need to use the string 'src' again in my java code?

1 Answer 1

5

Instead use the TypedArray

public CustomView(final Context context) {
    this(context, null);
}

public CustomView(final Context context,
            final AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomView(final Context context,
            final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);

    final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.Custom, defStyle, 0);

    int src = a.getInt(R.styleable.Custom_src, 0);

    a.recycle();
}
Sign up to request clarification or add additional context in comments.

Comments

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.