开发者

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 Attribu开发者_如何学GoteSet 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


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.


Looks like your XML(R.style.my_stylez) doesn't exist, or your R file is outdated.


Whenever you make new additions to the res directory it's a good idea to clean and build the project. But since ADT 15 this does not always work well. You sometimes have to go a step further and delete the bin directory as well as the gen directory.

After adt recreates those two directories, try running a clean again.


It seems pretty clear from looking around that it just isn't possible. Sorry. I truly wish this were possible...


The getXml method will read from res/xml, not from res/values, I think the idea is that you use one of the other other methods for getting the data, such as

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomTheme);

and then grab values out of the TypedArray:

thingColor = a.getColor(R.styleale.myCustomColor, res.getColor(R.color.myDefaultColor));

This works for styleables, however my problem is getting the AttributeSet attrs from XML in the first place to use as overrides, and allowing people to specify which XML file they want at run time, inflate it into an AttributeSet and pass it on.

I'll post back when I have an answer for the second part, but the code samples should solve

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜