Storing R.drawable IDs in XML array

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

I would like to store drawable resources' ID in the form of R.drawable.* inside an array using an XML values file, and then retrieve the array in my activity.

Any ideas of how to achieve this?

回答1:

You use a typed array in arrays.xml file within your /res folder that looks like this:

@drawable/car_01@drawable/balloon_random_02@drawable/dog_03

Then in your activity, access them like so:

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(); 


回答2:

In the value folder create xml file name it arrays.xml add the data to it in this way

@drawable/1@drawable/2@drawable/3@drawable/4

Then obtain it to your code this way

private TypedArray img; img = getResources().obtainTypedArray(R.array.your_array_name); 

Then to use a Drawable of these in the img TypedArray for example as an ImageView background use the following code

ImageView.setBackgroundResource(img.getResourceId(index, defaultValue)); 

where index is the Drawable index. defaultValue is a value you give if there is no item at this index

For more information about TypedArray visit this link http://developer.android.com/reference/android/content/res/TypedArray.html



回答3:

You can use this to create an array of other resources, such as drawables. Note that the array is not required to be homogeneous, so you can create an array of mixed resource types, but you must be aware of what and where the data types are in the array.

 @drawable/home@drawable/settings@drawable/logout#FFFF0000#FF00FF00#FF0000FF

And obtain the resources in your activity like this

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); 

Enjoy!!!!!



回答4:

You can't store arrays in R.drawable as far as I know.

What you can do is create an array in config.xml or strings.xml that maps a path to a drawable resource by using an alias resource.

See if this works, and please let me know if you need any additional help.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!