Roland
Roland

Reputation: 7863

I cannot read the AttributeSet from my XML resources

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 = getResources();
        XmlResourceParser parser = r.getXml(R.layout.testcameraoverlay);
        AttributeSet as = Xml.asAttributeSet(parser);

        int count = as.getAttributeCount(); //count is 0!!??

count == 0, so Android is not reading any attributes at all!

The XML file(R.layout.testcameraoverlay):

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:text="@string/app_name" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content">
</TextView>

Why can't I read the attributes?

Upvotes: 13

Views: 8408

Answers (2)

joen
joen

Reputation: 644

If I understand right, you need to read the attributes from the TextView for example the Text inside the TextView or the ID and so on?

I would make it as follows:

TextView text_res = (TextView) findViewById(R.id.TextView01);

String text_inTextView;
String id_fromTextView;

text_inTextView = text_res.getText();
id_fromTextView = String.valueOf(text_res.getId());

and so on...

I hope this is what you need.

Upvotes: 0

Roland
Roland

Reputation: 7863

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

Upvotes: 17

Related Questions