我无法从我的XML资源阅读的AttributeSet [英] I cannot read the AttributeSet from my XML resources

查看:247
本文介绍了我无法从我的XML资源阅读的AttributeSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取XML资源文件中的AttributeSet。 有关code是如下:

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!!??

计数== 0,因此Android是不是读任何属性可言!

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

XML文件(R.layout.testcameraoverlay):

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?

推荐答案

问题是解析器的功能的误解。该行经过:

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

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

分析器是在文档的开始,还没有读取的任何元件,因此也就不存在属性集中因为属性当然总是相对于当前元素。因此,要解决这个问题,我不得不做的是遍历元素,直到我得到以下为TextView的

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

这篇关于我无法从我的XML资源阅读的AttributeSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆