I cannot read the AttributeSet from my XML resources

后端 未结 2 2015
孤独总比滥情好
孤独总比滥情好 2021-02-07 17:44

I\'m trying to read an AttributeSet from an XML resource file. The relevant code is the following:

//This happens inside an Activity
        Resources r = getRe         


        
2条回答
  •  庸人自扰
    2021-02-07 18:05

    The problem was a misunderstanding of the functioning of the parser. After the line:

    XmlResourceParser parser = r.getXml(R.layout.testcameraoverlay);
    

    the parser is at the beginning of the document and hasn't yet read any element, therefore there is no attributeset because the attributes are of course always relative to the current element. So to fix this I had to do the following which is iterating over the elements until I get to "TextView":

        AttributeSet as = null;
        Resources r = getResources();
        XmlResourceParser parser = r.getLayout(R.layout.testcameraoverlay);
    
        int state = 0;
        do {
            try {
                state = parser.next();
            } catch (XmlPullParserException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }       
            if (state == XmlPullParser.START_TAG) {
                if (parser.getName().equals("TextView")) {
                    as = Xml.asAttributeSet(parser);
                    break;
                }
            }
        } while(state != XmlPullParser.END_DOCUMENT);
    

提交回复
热议问题