您的位置:首页 > 移动开发 > Android开发

Android中通过代码获取arrays.xml文件中的数据

2016-05-17 11:42 771 查看
android工程res/valuse文件夹下的arrays.xml文件中用于放各种数组数据,比如字符串数组、整型数组等,数组中的数据可能是具体的值,也有可能是对资源数据的引用,下面针对这两种情况通过代码来获取相应的数组数据。

一、数组中的数据为具体的值:

比如arrays.xml文件中的数组如下:

<string-array name="select_dialog_items">

<item>Command one</item>

<item>Command two</item>

<item>Command three</item>

<item>Command four</item>

</string-array>

代码中获取该数组资源的具体代码如下:

String[] items = getResources().getStringArray(R.array.select_dialog_items);

items数组中的数据就是arrays.xml文件中对应资源id R.array.select_dialog_items中的数据;

数据为其它类型的数组也可以通过Resources类中相应的方法获取,比如:

获取整型数组的数据方法为:

public int[] getIntArray(int id) throws NotFoundException

获取文本数组的数据方法为:

public CharSequence[] getTextArray(int id) throws NotFoundException

二、数组中的数据为对资源数据的引用:

比如arrays.xml文件中的数组如下:

<string-array name="feed_icons">

<item>@drawable/latest</item>

<item>@drawable/video</item>

<item>@drawable/world</item>

<item>@drawable/sports</item>

<item>@drawable/arts</item>

<item>@drawable/dining</item>

</string-array>

代码中获取该数组资源的具体代码如下:

TypedArray typedArray = getResources().obtainTypedArray(R.array.feed_icons);

String[] titleArr = getResources().getStringArray(R.array.feed_names);

if( null != titleArr ){

int titleLength = titleArr.length;

for( int index = 0; index < titleLength; index++ ){

int feedResId = typedArray.getResourceId( index, 0 );

//...

}

}

获取arrays.xml中数据项为引用资源数据的数组时,首先通过Resources类中的obtainTypedArray方法获取到TypedArray实例,然后通过TypedArray方法中的getResourcesId方法获取数组中每一项的资源id,这样就能顺利地引用到数组中资源了。

通过代码获取arrays.xml中的数组资源时,数组中的元素项不宜过多,特别是一次性获取的时候,有可能你在使用时它还没有获取到你需要使用的数组项。

END

注意事项

通过android的arrays.xml获取数组信息时,在代码中初始化数组时建议通过线程初始化,避免在初始化的时候阻塞UI线程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: