加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:19:13 所属栏目:百科 来源:网络整理
导读:arrays.xml文件中用于放各种数组数据,比如字符串数组、整型数组等,数组中的数据可能是具体的值,也有可能是对资源数据的引用,下面针对这两种情况通过代码来获取相应的数组数据。 一、数组中的数据为具体的值: arrays.xml文件中的数组如下: string-array

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中的数组资源时,数组中的元素项不宜过多,特别是一次性获取的时候,有可能你在使用时它还没有获取到你需要使用的数组项。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读