从资源中随机选择图像

3

你好,我正在开发一个简单的安卓应用。这个应用只包含一个图片视图。当点击图片视图时,应该显示不同的图片。我的问题是如何通过索引获取资源列表或资源图片。例如,在drawable文件夹中,我有100张图片,它们的名称从s1到s100。我想使用随机函数之一来显示其中的一张图片,类似于以下方式:

private void ImageView_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int index = r.Next() % 100;

            //code where I get picture on "index place" from my drawable folder.
        }

谢谢!

4个回答

2
在values文件夹中创建任何arrays.xml文件,并像这样将您的可绘制对象添加到数组中:
<integer-array name="images">
    <item>@drawable/drawable1</item>
    <item>@drawable/drawable2</item>
    <item>@drawable/drawable3</item>
</integer-array>

接下来,在您的活动类中添加以下内容:

TypedArray images = getResources().obtainTypedArray(R.array.images);

// get resource id by random index i
images.getResourceId(i, -1)

2

我看到你已经有了一个被接受的答案,但这是一种非常无聊的方式来实现你想要的,因为它需要开发者编写包含数百个项目的数组。更简单的方法是直接获取可绘制对象的标识符。

我不确定在Xamarin/C#上如何实现,但在Java中你可以这样使用:

Random r = new Random();
int index = r.nextInt(100);
String name = "s" + index;
int drawableId = getResources().getIdentifier(
                    name,               // the name of the resource
                    "drawable",         // type of resource
                    getPackageName())); // your app package name
imageView.setImageResource(drawableId);

1

创建一个整数数组来存储所有的可绘制对象。

int resIds = new int[]{R.drawable.s1, R.drawable.s2, .... R.drawable.s100};

然后计算随机索引并从该索引中选择可绘制项。
Random r = new Random();
int index = r.Next(resIds.length -1);
imageView.setImageResource(resIds[index]);

我是否需要添加 using 语句来访问 R? - Petar Mijović
你为什么接受这个答案?谁想要创建这样的整数数组?@Budius的答案就是你需要的。而且最好的答案甚至还没有发布,因为可以简单地列出drawable文件夹中的内容。 - greenapps

0

这是最优雅的解决方案,@Budius 给出了 Java 版本,这是 C# 版本:

private void ImageView_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int index = r.Next() % 36;
            String name = "s" + index;
            int drawableId = Resources.GetIdentifier(
                                name,               // the name of the resource
                                "drawable",         // type of resource
                                "Us.Us"); // your app package name
            imageView.SetImageResource(drawableId);

        }

"Us.Us" 是我的包名。

看起来像我的答案。只是说一下。 - Budius
1
@Budius 对不起,我看错了。谢谢。 - Petar Mijović

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接