从机器人绘制的文件夹随机genaration形象 [英] random genaration of image from drawable folder in android

查看:168
本文介绍了从机器人绘制的文件夹随机genaration形象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android版本:4.2
我开发一个Android应用程序。我需要生成绘制文件夹的图像随机。在我绘制我有45的图像以不同的名称。 我的XML code是:

Android version:4.2
I am developing an android App. I need to generate images from drawable folder randomly. In my drawable I have 45 images with different names. My xml code is:

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

我曾尝试与该code:

I have tried with this code:

ImageView img=(ImageView)findViewById(R.id.imageView1);
Random rand = new Random();
int rndInt = rand.nextInt(52) + 1;
String drawableName = "photo"+ rndInt;

int resID = getResources().getIdentifier(drawableName, "drawable",  getPackageName());
img.setImageResource(resID);

但有了这个code,我需要改变我的形象名称照片1 照片2 ,..而我并不想这样做。

But with this code I need to change my image names to photo1, photo2, ... and I don't want to do it.

这是如何实现它的任何建议?谢谢你。

Any suggestion on how to implement it? Thank you.

推荐答案

一种方法是创建所需的图像的ID的数组。并采取随机一名来自该阵列。这种方法是在其他的答案解释。

One way is to create an array with required image's ids. And take random one from that array. That approach is explained in other answers.

另一种方法是创建值文件 random_images_array.xml 项目的文件夹,然后满足它是这样的:

Another way is to create file random_images_array.xml in values folder of your project and fill it like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <array name="apptour">
        <item>@drawable/image_1</item>
        <item>@drawable/photo_2</item>
        <item>@drawable/picture_4</item>
    </array>

</resources>

然后你可以采取随机图像从XML数组:

And then you can take random image from that xml array:

final TypedArray imgs = getResources().obtainTypedArray(R.array.random_images_array);
final Random rand = new Random();
final int rndInt = rand.nextInt(imgs.length());
final int resID = imgs.getResourceId(rndInt, 0);

第三个方法是取随机场从R.drawable类:

Third method is to take random field from R.drawable class:

final Class drawableClass = R.drawable.class;
final Field[] fields = drawableClass.getFields();

final Random rand = new Random();
int rndInt = rand.nextInt(fields.length);
try {
    int resID = fields[rndInt].getInt(drawableClass);
    img.setImageResource(resID);
} catch (Exception e) {
    e.printStackTrace();
}

这篇关于从机器人绘制的文件夹随机genaration形象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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