2011-01-24 16 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を呼び出すかどうか疑問に思っています。 –

答えて

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

私もあなたに感謝します。 –

0

、あなたはのTextViewまたはID内のテキストなど例えばのTextViewから属性を読み取るする必要がありますか?次のように私はそれを作るだろう

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

関連する問題