我正在使用XmlPullParser
解析布局文件,我需要计算内部标记才能识别子视图。我找到了计算每个标签属性的方法,但无法找到如何精确计算标签。
我有这样的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0d3fff"
android:text="New Button 1"
android:layout_marginRight="10dp"
android:id="@+id/btnDef1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnDef2"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tv1"/>
</LinearLayout>
任何人都有想法如何计算标记为LinearLayout
的孩子?
提前谢谢。
答案 0 :(得分:2)
我不知道为什么有人想要从布局文件中计算标签。如果要对布局进行充气,请使用getChildCount方法或使用以下代码来获取LinearLayout的子项数
int childcount = ll.getChildCount();
for (int i=0; i < childcount; i++){
View v = ll.getChildAt(i);
}
如果你倾向于使用XMLPullparser,我不认为有任何直接的方法来计算xml标签。你必须浏览每个标签
int count = 0;
XmlPullParser xpp = factory.newPullParser();
try {
xpp.setInput(new InputStreamReader(is));
int eventType = xpp.next();
Project p = null;
while(eventType != XmlPullParser.END_DOCUMENT) {
count++;
String tagName = xpp.getName();
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
// and other cases that you want to handle
}
}
} catch (Exception e) {
e.printStackTrace();
}