我想使用XML值文件将可提取资源的ID以R.drawable.*
的形式存储在数组中,然后在我的activity中检索该数组。
你有什么办法实现这一点吗?
发布于 2011-08-05 01:24:23
您可以在/res/values
文件夹内的arrays.xml
文件中使用如下所示的typed array:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer-array name="random_imgs">
<item>@drawable/car_01</item>
<item>@drawable/balloon_random_02</item>
<item>@drawable/dog_03</item>
</integer-array>
</resources>
然后在您的活动中,像这样访问它们:
TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);
// get resource ID by index, use 0 as default to set null resource
imgs.getResourceId(i, 0)
// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, 0));
// recycle the array
imgs.recycle();
发布于 2015-09-29 02:12:10
在value
文件夹中,创建xml
文件,将其命名为arrays.xml
,以这种方式向其中添加数据
<integer-array name="your_array_name">
<item>@drawable/1</item>
<item>@drawable/2</item>
<item>@drawable/3</item>
<item>@drawable/4</item>
</integer-array>
然后以这种方式将其获取到您的代码
private TypedArray img;
img = getResources().obtainTypedArray(R.array.your_array_name);
然后,要在img
TypedArray
中使用这些内容的Drawable
,例如作为ImageView
background
,请使用以下代码
ImageView.setBackgroundResource(img.getResourceId(index, defaultValue));
其中index
是Drawable
索引。如果此index
中没有项目,则defaultValue
是您所给出的值
有关TypedArray
的更多信息,请访问此链接http://developer.android.com/reference/android/content/res/TypedArray.html
发布于 2015-07-08 00:24:04
您可以使用它来创建其他资源的数组,例如可绘制的资源。请注意,不要求数组是同构的,因此您可以创建混合资源类型的数组,但您必须了解数据类型在数组中的内容和位置。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<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>
并获取活动中的资源,如下所示
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);
享受吧!
https://stackoverflow.com/questions/6945678
复制相似问题