سؤال

I've created a custom View subclass with the following constructor:

public MyCustomView(Context context, AttributeSet attrs)
{
    super(context, attrs);

    // get custom "thingy" attribute specified in XML
    int thingy = attrs.getAttributeIntValue(MY_NAMESPACE, "thingy", 0);

    //rest of constructor
    ...
}

As can be seen, it grabs a custom "thingy" attribute from its XML attributes. This works absolutely fine, and I have had no problems so far. Why then, does Google tell you to define a custom View's XML attributes in a declare-styleable in res/values/attrs.xml (discussed here) and to apply them by calling context.getTheme().obtainStyledAttributes() (discussed here)?

هل كانت مفيدة؟

المحلول

I'm dumb. The second link I posted does explain why:

When a view is created from an XML layout, all of the attributes in the XML tag are read from the resource bundle and passed into the view's constructor as an AttributeSet. Although it's possible to read values from the AttributeSet directly, doing so has some disadvantages:

  • Resource references within attribute values are not resolved
  • Styles are not applied

Instead, pass the AttributeSet to obtainStyledAttributes(). This method passes back a TypedArray array of values that have already been dereferenced and styled.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top