原始 XML 資源文件一般保存在 /res/xml 路徑下羹唠。
簡單的使用示例如下:
首先是我們保存在 /res/xml 路徑下的資源文件 test_xml01.xml 的內(nèi)容:
<?xml version="1.0" encoding="utf-8"?>
<Tests>
<Test index="0" size="1">Test01</Test>
<Test index="1" size="2">Test02</Test>
<Test index="2" size="3">Test03</Test>
</Tests>
主布局文件的內(nèi)容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGray"
android:orientation="vertical"
android:id="@+id/container"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/show"
android:layout_marginTop="20dp"
android:onClick="show"
/>
<TextView
android:id="@+id/showText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
/>
</LinearLayout>
主程序文件的代碼:
package com.toby.personal.testlistview;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
final private static String TAG = "Toby_Test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void show(View view) {
XmlResourceParser xmlResourceParser = getResources().getXml(R.xml.test_xml01);
try {
StringBuilder stringBuilder = new StringBuilder("");
while (xmlResourceParser.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xmlResourceParser.getEventType() == XmlResourceParser.START_TAG) {
String tagName = xmlResourceParser.getName();
if(tagName.equals("Test")) {
String testIndex = xmlResourceParser.getAttributeValue(null, "index");
stringBuilder.append("index: ");
stringBuilder.append(testIndex);
stringBuilder.append("\t");
String testSize = xmlResourceParser.getAttributeValue(1);
stringBuilder.append("size: ");
stringBuilder.append(testSize);
stringBuilder.append("\t");
stringBuilder.append("name: ");
stringBuilder.append(xmlResourceParser.nextText());
}
stringBuilder.append("\n");
}
xmlResourceParser.next();
}
TextView showText = (TextView) findViewById(R.id.showText);
showText.setText(stringBuilder.toString());
} catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
}
}
程序的運(yùn)行效果:
參考文獻(xiàn):《瘋狂Android講義(第2版)》