2014-06-10 35 views
1

我想拉出所有已在活動中分配了id的TextView,以便用動態值填充它們。爲了這樣做,我使用XMLResourceParser來檢查標籤並獲取標識。下面的代碼:xml資源解析器無法識別id屬性

public int[] getElementIds(int layoutId, String viewType) 
    throws XmlPullParserException, IOException{ 
    XmlResourceParser parser = activity.getResources().getLayout(layoutId); 
    LinkedList<Integer> idList = new LinkedList<Integer>(); 
    while(parser.getEventType()!=XmlResourceParser.END_DOCUMENT){ 
     parser.next(); 
     if(parser.getEventType()==XmlResourceParser.START_TAG){ 
      if(parser.getName().equals(viewType)){ 
      idList.add(parser.getIdAttributeResourceValue(0)); //here's the problem 
      } 
     } 
    } 
    // returns an int[] from values collected 
} 

與註釋的行只是給我回零,我指定的默認值。然而,下面的代碼工作,屬性索引通過反覆試驗得出:

idList.add(parser.getAttributeResourceValue(0, 1)); // the zero here is 'id' attribute index 

任何想法?

回答

0

經過額外的研究,似乎我發現了API中的一個錯誤。在線可用的代碼如下所示:

public int getIdAttributeResourceValue(int defaultValue) { 
     return getAttributeResourceValue(null, "id", defaultValue); 
} 

public int getAttributeResourceValue(String namespace, String attribute, int defaultValue) { 
     int idx = nativeGetAttributeIndex(mParseState, namespace, attribute); 
     if (idx >= 0) { 
      return getAttributeResourceValue(idx, defaultValue); 
     } 
    return defaultValue; 
} 

public int getAttributeResourceValue(int idx, int defaultValue) { 
     int t = nativeGetAttributeDataType(mParseState, idx); 
     // Note: don't attempt to convert any other types, because 
     // we want to count on appt doing the conversion for us. 
     if (t == TypedValue.TYPE_REFERENCE) { 
      return nativeGetAttributeData(mParseState, idx); 
     } 
     return defaultValue; 
} 

其中最後一個函數是實際執行工作的函數。沒有這個類的文檔(XMLBlock),我沒有訪問實際上用C編寫的函數。我所知道的是,這裏的違規函數是第二個,名字空間和屬性名稱是參數。對於屬性名稱'style'來說它可以正常工作,但對於'id'(這是在另一個地方由API提供的名稱,以及由返回屬性名稱的不同函數返回的值,提供給定索引),它不會不會提出任何問題,並持續吐出默認值。此外,通過使用其參數是屬性索引而非名稱的函數(上面複製的最後一個函數),我可以通過可以訪問那些相同的id值。結論:「本地」代碼處理名稱「id」的方式有些混亂。我正在向開源項目發送一個錯誤報告,並且會發布我收到的任何響應。

+0

你有問題數,? – TmTron

+1

我現在甚至找不到問題記者。但我可以在[github](https://github.com/jegesh/Android-simple-XML-Parser)上指出我的解決方法! – ygesher

+0

也許[#36997052](https://issuetracker.google.com/issues/36997052)? – TmTron

0

作爲一種變通方法,我在我自己的代碼來實現此功能:您報告

private int getIdAttributeResourceValue(XmlResourceParser parser) { 
    final int DEFAULT_RETURN_VALUE = 0; 
    for (int i = 0; i < parser.getAttributeCount(); i++) { 
     String attrName = parser.getAttributeName(i); 
     if ("id".equalsIgnoreCase(attrName)) { 
      return parser.getAttributeResourceValue(i, DEFAULT_RETURN_VALUE); 
     } 
    } 
    return DEFAULT_RETURN_VALUE; 
}