可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to display a random image from the bunch of images i have stored in res/drawable.
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 :)
Thanks
Chinmay
回答1:
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");
The documentation for this method says:
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.
Alternatively, if you don't mind listing the resources in XML, you could create a typed array that you can then randomly select from.
回答2:
I realize this is a super old question, but wanted to provide a good solution for any Googlers.
Access resources by name is much less efficient than by id. The whole point of the resource system is so that you don't have to resolve names, and can use ids instead.
What you need to do is utilize the Array Resource type. Follow along with my easy steps! I make random images...Fun!
Create an array resource that includes all of the images you want to choose from. I put this in my res/values/arrays.xml
file but it can really go anywhere.
<array name="loading_images">
<item>@drawable/bg_loading_1</item>
<item>@drawable/bg_loading_2</item>
<item>@drawable/bg_loading_3</item>
<item>@drawable/bg_loading_5</item>
<item>@drawable/bg_loading_6</item>
<item>@drawable/bg_loading_7</item>
<item>@drawable/bg_loading_8</item>
</array>
Next, get the TypedArray
from the Resources
and use that to choose a random image.
TypedArray images = getResources().obtainTypedArray(R.array.loading_images);
int choice = (int) (Math.random() * images.length());
mImageView.setImageResource(images.getResourceId(choice, R.drawable.bg_loading_1));
images.recycle();
Profit!
回答3:
The items in res/drawable are enumerated in the R.drawable class at compile time. You could probably use reflection to get a list of the members of that class, and then select from that list randomly.
回答4:
I can't think of anything you can do at runtime. You could possibly create an array of address integers (since the R.drawable.xxxx
is essentially an integer address) and then use java.util.Random
to select a random resource address from your array.
回答5:
If you knew you had X images to choose from could use random.nextInt(X) to randomly generate an integer between 0 (inclusive) and X (exclusive), then switch on it to pick your resource:
Random mRand = new Random();
int x = mRand.nextInt(8);
switch (x) {
case 0:
mResource = R.id.someresource1
case 1:
mResource = R.id.someresource2
...
case X:
mResource = R.id.someresourceX
}
回答6:
I have never used the AssetManager, but would you be able to call getAssets on your Resources class, and then call list on the AssetManager with the location of your resources?
回答7:
If you don't mind setting up a <level-list>
XML file, you should be able to use a LevelListDrawable
and call setImageLevel()
with your random number.
If you don't want to change this list when you add files, I would assume there is some way of setting up a build event where you could progmatically generate this file.
回答8:
I did this in my Applez application as follows;
1) create an ArrayList to hold images and fill it
2) take random number and return corresponding image.
in code :
public static void fruitInventory() {
fruitResources.clear();
Field[] fields = R.drawable.class.getFields();
for (Field field : fields) {
// Take only those with name starting with "fr"
if (field.getName().startsWith("fr_")) {
try {
String FType = field.getName().substring(3);
fruitResources.add(field.getInt(null));
alfruitTypes.add(FType);
Log.d("FruitManager", "Type " + FType);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
and to add the fruit :
public static void addFruit(Context context){
fruitInventory();
for (int i = 0; i < 10; i++) {
Random Rnd = new Random();
int FruitType = Rnd.nextInt(fruitResources.size());
GameObject nextApple = new GameObject(BitmapFactory.decodeResource(context.getResources(),
fruitResources.get(FruitType)), FruitType);
MainGamePanel.AppleList.add(nextApple);
}
}
Idea was (and works) that I could add extra fruits to the game, simply by adding for instance "fr_eggplant.bmp" to the images folder.