android 资源数组的获取

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

        比如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

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

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

猜你喜欢

转载自blog.csdn.net/weixin_37744986/article/details/81026246
今日推荐