---
title: "android array.xml中使用图片和颜色资源"
author: "喧嚣求静"
date: "2015-08-23T11:17:57Z"
tags: []
categories: ["移动开发"]
slug: "android-array-xml"
draft: false
lastmod: "2015-08-23T11:17:57Z"
id: 2237366
url: "https://913.iteye.com/blog/2237366"
---

```
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="home_grid_texts">
        <item>转账</item>
        <item>余额宝</item>
        <item>手机充值</item>
        <item>信用卡还款</item>
    </string-array>
    <array name="icons">
        <item>@drawable/home</item>
        <item>@drawable/settings</item>
        <item>@drawable/logout</item>
    </array>
    <array name="colors">
        <item>#FFFF0000</item>
        <item>#FF00FF00</item>
        <item>#FF0000FF</item>
    </array>
</resources>
```

 常用方法：

```
img_text=mContext.getResources().getStringArray(R.array.home_grid_texts);
	//此方案不行	
    //imgs=mContext.getResources().getIntArray(R.array.home_grid_imgs);
  TypedArray ar = mContext.getResources().obtainTypedArray(R.array.home_grid_imgs);
		int len = ar.length();     
		//int[] resIds = new int[len];     
		imgs=new int[len]; 
		for (int i = 0; i < len; i++){     
		    //resIds[i] = ar.getResourceId(i, 0);
			imgs[i]=ar.getResourceId(i, 0);
		}
		ar.recycle();
```

```
Resources res = getResources();
TypedArray icons = res.obtainTypedArray(R.array.icons);
Drawable drawable = icons.getDrawable(0);

TypedArray colors = res.obtainTypedArray(R.array.colors);
int color = colors.getColor(0,0);
```

```

```

 

 

参考：[http://stackoverflow.com/questions/6945678/android-storing-r-drawable-ids-in-xml-array](http://stackoverflow.com/questions/6945678/android-storing-r-drawable-ids-in-xml-array)