以前にあなたと同様の問題に遭遇しました。Android には、res->values XML ファイル内のキーと値のペアを読み取るためのツールがないと思います。res-> values ディレクトリではなく、assets ディレクトリに XML ファイルを保存します。次に、Activity から、assets フォルダー内の XML ファイルを読み取ります。次のコードが機能すると思います。私はそれをテストしませんでした。うまくいかない場合は、お知らせください。
assets フォルダー内に、「myPoints」という名前の XML ドキュメントを配置できます。
<resources>
<point Pointz="Point1">
<item Xpoint="100.340"></item>
<item Ypoint="200.000"></item>
</point>
<point Pointz="Point2">
<item Xpoint="350.450"></item>
<item Ypoint="400.900"></item>
</point>
<end></end>
</resources>
あなたの活動で:
Double Xpoint, Ypoint;
int PointNum;
//Call the ReadXML() method somewhere in onCreate
private void ReadXML() {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
GetXML_Handler doingWork = new GetXML_Handler();
xr.setContentHandler(doingWork);
InputSource Isource = new InputSource(this.getActivity().getAssets().open("myPoints.xml"));
xr.parse(Isource);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
//This is a private class inside whatever Acitivity u are in.
private class GetXML_Handler extends DefaultHandler {
boolean foundWord = false;
int i = 0;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equals("point")) {
foundWord = true;
PointNum = attributes.getValue("Pointz"); //so PointNum will either be saved as "Point1" or "Point2"
}
} else if (foundWord == true && localName.equals("item")) {
Xpoint = attributes.getValue(0);
Ypoint = attributes.getValue(1);
} else if (localName.equals("end")) {
foundWord = false;
}
} // End of startElement
}// End of Private Class GetXML_Handler
res-> values フォルダー内に XML ファイルを保存することを主張する場合、ポイントを 2 つの方法で保存できます。
<string-array name="points">
<item>100.340</item> //X coordinate #1
<item>200.000</item> //Y coordinate #1
<item>350.450</item> //X coordinate #2
<item>400.900</item> //Y coordinate #2
</string-array>
2 番目の方法は、2 つの配列として保存することです。X 座標用の 1 つの配列と Y 座標用の 1 つの配列。
<string-array name="Xpoints">
<item>100.340</item> //X coordinate #1
<item>350.450</item> //X coordinate #2
</string-array>
<string-array name="Ypoints">
<item>200.000</item> //Y coordinate #1
<item>400.900</item> //Y coordinate #2
</string-array>