我想将可绘制资源的ID以R.drawable.*
的形式存储在一个XML值文件中的数组中,然后在我的活动中检索该数组。
有什么好的方法实现这个功能吗?
我想将可绘制资源的ID以R.drawable.*
的形式存储在一个XML值文件中的数组中,然后在我的活动中检索该数组。
有什么好的方法实现这个功能吗?
你在/res/values
文件夹下使用了一个名为arrays.xml
的文件,并且在文件中使用了一个类型数组,该数组看起来像这样:
<?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>
然后在您的Activity中,可以这样访问它们:
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();
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);
然后,要在 TypedArray
中使用这些的Drawable
,例如作为ImageView
的背景,请使用以下代码:
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.my_drawable);
ImageView imageView = findViewById(R.id.my_image_view);
imageView.setBackground(drawable);
ImageView.setBackgroundResource(img.getResourceId(index, defaultValue));
其中index
是Drawable
索引。defaultValue
是当该index
处没有条目时给出的值。
有关TypedArray
的更多信息,请访问此链接:http://developer.android.com/reference/android/content/res/TypedArray.html
您可以使用此功能创建其他资源的数组,例如可绘制对象。请注意,该数组不需要是同质的,因此您可以创建混合资源类型的数组,但必须知道数组中数据类型的内容和位置。
<?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);
享受吧!!!!!
在 Kotlin 中,你可以这样做:
<integer-array name="drawer_icons">
<item>@drawable/drawer_home</item>
</integer-array>
您将从资源中获取图像数组,类型为TypedArray
val imageArray = resources.obtainTypedArray(R.array.drawer_icons)
通过索引获取资源 ID
imageArray.getResourceId(imageArray.getIndex(0),-1)
或者您可以将imageView的资源设置为id
imageView.setImageResource(imageArray.getResourceId(imageArray.getIndex(0),-1))
最后一次循环中,重新利用该数组
imageArray.recycle()
kotlin way could be this:
fun Int.resDrawableArray(context: Context, index: Int, block: (drawableResId: Int) -> Unit) {
val array = context.resources.obtainTypedArray(this)
block(array.getResourceId(index, -1))
array.recycle()
}
R.array.random_imgs.resDrawableArray(context, 0) {
mImgView1.setImageResource(it)
}