Reputation: 110670
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?
Upvotes: 3
Views: 3524
Reputation: 41972
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();
}
Upvotes: 5