2011-01-24 64 views
12

我试图从XML资源文件中读取AttributeSet。 相关的代码如下:我无法从我的XML资源中读取AttributeSet

//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,因此Android是不读任何属性了!

XML文件(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> 

为什么我不能读取属性?

+0

我对此没有太多的工作,但是你知道如果你从根元素开始或者如果解析器在根元素之前启动?我想知道如果你调用getnext,如果这会将你移动到根元素或不。 – 2011-01-24 23:06:48

回答

15

问题在于对解析器功能的误解。行后:

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

解析器在文档的开头,还没有读取任何元素,因此也就不存在属性集中,因为属性当然总是相对于当前元素。所以要解决这个问题,我不得不做下列迭代元素,直到我到达“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); 
+2

我也谢谢你。 – 2014-03-10 04:22:07

0

如果我理解正确的,你需要从的TextView例如的TextView或ID中的文本等读取属性?

如下我将使它:

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

等等...

我希望这是你所需要的。

+0

没有。在这种情况下,TextView甚至不存在,而是包含在XML资源文件中。我想阅读这个资源文件并从它创建一个TextView,但我没有得到任何属性。 – Roland 2011-01-25 15:12:42