gam*_*tor 141 arrays android android-xml android-resources android-drawable
我想R.drawable.*
使用XML值文件以数组内部的形式存储可绘制资源的ID ,然后在我的活动中检索数组.
有关如何实现这一目标的任何想法?
Pat*_*fka 351
您在文件夹中的文件中使用类型化的数组,如下所示:arrays.xml
/res/values
<?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>
Run Code Online (Sandbox Code Playgroud)
然后在您的活动中,像这样访问它们:
TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);
// get resource ID by index
imgs.getResourceId(i, -1)
// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, -1));
// recycle the array
imgs.recycle();
Run Code Online (Sandbox Code Playgroud)
ahm*_*yem 30
在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>
Run Code Online (Sandbox Code Playgroud)
然后通过这种方式获取代码
private TypedArray img;
img = getResources().obtainTypedArray(R.array.your_array_name);
Run Code Online (Sandbox Code Playgroud)
然后Drawable
在img
TypedArray
例如ImageView
background
使用以下代码中使用这些
ImageView.setBackgroundResource(img.getResourceId(index, defaultValue));
Run Code Online (Sandbox Code Playgroud)
其中index
是Drawable
索引.
defaultValue
如果此处没有项目,则为您提供的值index
有关TypedArray
访问此链接的更多信息,请访问
http://developer.android.com/reference/android/content/res/TypedArray.html
yub*_*del 14
您可以使用它来创建其他资源的数组,例如drawables.请注意,数组不需要是同类的,因此您可以创建混合资源类型的数组,但是您必须知道数组中数据类型的位置和位置.
<?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>
Run Code Online (Sandbox Code Playgroud)
并像这样获取您活动中的资源
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);
Run Code Online (Sandbox Code Playgroud)
请享用!!!!!
在 Kotlin 中,你可以这样做:-
<integer-array name="drawer_icons">
<item>@drawable/drawer_home</item>
</integer-array>
Run Code Online (Sandbox Code Playgroud)
您将从资源中获取图像数组,如下所示TypedArray
val imageArray = resources.obtainTypedArray(R.array.drawer_icons)
Run Code Online (Sandbox Code Playgroud)
通过索引获取资源ID
imageArray.getResourceId(imageArray.getIndex(0),-1)
Run Code Online (Sandbox Code Playgroud)
或者您可以将 imageView 的资源设置为 id
imageView.setImageResource(imageArray.getResourceId(imageArray.getIndex(0),-1))
Run Code Online (Sandbox Code Playgroud)
最后回收数组
imageArray.recycle()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
83572 次 |
最近记录: |