如何从资源中随机选择(R.drawable.xxxx) [英] how to select from resources randomly (R.drawable.xxxx)

查看:77
本文介绍了如何从资源中随机选择(R.drawable.xxxx)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我存储在res/drawable中的一堆图像中显示一个随机图像.

I want to display a random image from the bunch of images i have stored in res/drawable.

我知道的唯一技术是访问特定图像(如果您知道其资源ID).是否可以通过使用文件名或其他名称(可以在运行时构造)来访问图像?

The only technique that I know is to access a particular image if you know its resource id. Is there a way to access the images by using the filenames or something else (which can be constructed at runtime)?

我想在运行时随机选择一个图像.任何建议/想法表示赞赏:)

I want to randomly select an image at runtime. Any suggestions/ideas appreciated :)

谢谢 下巴

推荐答案

您还可以按名称访问资源,如果您知道资源的名称或可以根据某些名称派生它们,那么这可能是解决问题的可行方法.预定义的命名方案.

You can also access resources by name, which may be a viable approach to solving your problem if you know the names of the resources or can derive them according to some pre-defined naming scheme.

您必须使用

You have to map the name to the identifier using the getIdentifier method of the Resources class.

String name = "resource" + rng.nextInt(count);
int resource = getResources().getIdentifier(name, "drawable", "com.package");

此方法的文档说:

注意:此功能的使用是 灰心.效率更高 通过标识符检索资源 比按名称.

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

这是真的,但是如果您使用对性能不敏感的代码来执行此操作,则不必担心.

This is true but need not be a problem if you are doing it in code that isn't performance sensitive.

或者,如果您不介意以XML列出资源,则可以创建有类型的数组,您可以从中随机选择.

Alternatively, if you don't mind listing the resources in XML, you could create a typed array that you can then randomly select from.

这篇关于如何从资源中随机选择(R.drawable.xxxx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆