如何创建从style.xml的AttributeSet中的?style、xml、AttributeSet

2023-09-06 02:40:59 作者:低智商对象i

下面是我的故事:

我得到了我想要从code使用predefined样式来创建一个自定义的ViewGroup,我的方法,到目前为止已建立从style.xml元素的AttributeSet中的对象,像这样(警告,提防复制粘贴$ C $领先C):

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);

但是这样做时,我得到一些疯狂的错误: ..android.content.res.Resources $ NotFoundException:资源ID#0x7f090002型#0×12是无效的

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.

感谢

推荐答案

您需要启动一个XML文件中的资源标识符,preferably在RES / XML。然后,你可以先创建一个XmlPullParser获得的AttributeSet:

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);

您可以在AOSP这在绘制CTS测试的例子。

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

 
精彩推荐
图片推荐