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>
items数组中的数据就是arrays.xml文件中对应资源id R.array.select_dialog_items中的数据;
- String[] items = getResources().getStringArray(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>
获取arrays.xml中数据项为引用资源数据的数组时,首先通过Resources类中的obtainTypedArray方法获取到TypedArray实例,然后通过TypedArray方法中的getResourcesId方法获取数组中每一项的资源id,这样就能顺利地引用到数组中资源了。
- 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中的数组资源时,数组中的元素项不宜过多,特别是一次性获取的时候,有可能你在使用时它还没有获取到你需要使用的数组项。