Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an AttributeSet from a style.xml?

Here's my story:

I got a custom ViewGroup that I want to create from code using a predefined style, my approach so far has been creating an AttributeSet object from a style.xml element, like so (warning, beware of the copy-paste code ahead):

    XmlPullParser parser = getResources().getXml(R.style.my_stylez);
    AttributeSet attributes = Xml.asAttributeSet(parser);

But when doing so I get some crazy error: "..android.content.res.Resources$NotFoundException: Resource ID #0x7f090002 type #0x12 is not valid"

I'm know I'm probably missing something very obvious here (or am I?), and would be grateful if any of you guys can point me in the right direction.

Thanks

like image 488
juanhawa Avatar asked Dec 10 '10 15:12

juanhawa


Video Answer


1 Answers

You need to start with a resource identifier for an XML file, preferably in res/xml. Then you can obtain an AttributeSet by first creating an XmlPullParser:

Resources res = context.getResources();
XmlPullParser parser = res.getXml(R.xml.some_xml_file);

// Seek to the first tag.
int type = 0;
while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
    type = parser.next();
}

// Wrap as an attribute set.
AttributeSet attrs = Xml.asAttributeSet(parser);

You can find examples of this in the drawable CTS tests in AOSP.

like image 126
alanv Avatar answered Oct 02 '22 16:10

alanv