[英]How getting an array of xml file from android resource?
I have this array into my resource file : 我将此数组放入我的资源文件中:
<array name="xml_data">
<item>@xml/data1</item>
<item>@xml/data2</item>
<item>@xml/data3</item>
<item>@xml/data4</item>
</array>
Normally, it's not different from an normal array, but when getting in code, this doesn't work... 通常,它与普通数组没有什么不同,但是在获取代码时,这是行不通的...
final Resources res = getResources();
int[] xmlList = res.getIntArray(R.array.xml_data);
Log.i(TAG, "Data found: "+ xmlList.length);
for (int i = 0; i < xmlList.length; i++) {
Log.i(TAG, "Extract xml id="+ xmlList[i].);
}
Here is the output obtained in the logcat : 这是在logcat中获得的输出:
Data found: 4
Extract xml id=0
Extract xml id=0
Extract xml id=0
Extract xml id=0
Can you help me about this? 您能帮我吗?
Thanks. 谢谢。
For your convenience lets take an example: 为了方便起见,请举一个例子:
I had a simple 'string' array( not int) in a sample xml file. 我在示例xml文件中有一个简单的“字符串”数组(不是int)。 Lets call it array.xml
让我们称之为array.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="doing">
<item>1</item>
<item>2/item>
<item>3/item>
<item>3</item>
</string-array>
</resources>
Now in my Java file, I called it as follows inside my OnCreate() function and it worked: 现在,在我的Java文件中,我在OnCreate()函数中按如下所示对其进行了调用,并且它可以正常工作:
String[] xmlList = getResources().getStringArray(R.array.doing);
int first = Integer.parseInt(xmlList[0]);
Log.d("test", "1st string is: " + first);
PS: I haven't tested the code but I hope you got the logic. PS:我尚未测试过代码,但我希望您理解逻辑。 All the best.
祝一切顺利。 Hope it helps.
希望能帮助到你。
Use your TypedArray like this: 像这样使用您的TypedArray:
TypedArray mTypedArray = getResources().getTypedArray(R.array.xml_data);
Then, retrieve your resource ID's like this: 然后,像这样检索您的资源ID:
int id = mTypedArray.getResourceId(position, defaultResourceId);
When I used this, it was an array of String IDs, so I followed that with this: 当我使用它时,它是一个字符串ID数组,因此我跟随着这个:
getString(id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.