1

我正在尝试ImageButton随机选择我使用的图片。

我认为这段代码应该可以工作,但是在将资源作为String.

    ImageButton getClickTime = (ImageButton) findViewById(R.id.clicker);

    Random generator = new Random();
    int generatedRandom = generator.nextInt(10) + 1;
    String randomImage = "R.drawable.bg" + (String.valueOf(generatedRandom)) ;
    Drawable replaceImage = getResources().getDrawable((int) randomImage);

    getClickTime.setImageDrawable((Drawable) replaceImage);

int我似乎对s、Strings、drawables 和s 的演员阵容有点混乱CharSequence

如果我手动输入随机选择的图像资源,它可以工作。但是如果我将它传递String给一个文本框,我可以看到它的写法与我手动输入时的写法完全相同。

谁能看到我在这里做错了什么?

提前致谢

4

3 回答 3

3

您的问题是您误解了 Android 如何使用资源 ID。该R文件包含int映射到应用程序中包含的资源的 ID。您试图drawable通过将其String引用转换为int. 这是不可能的,而且没有意义。

我建议您创建一个int[]包含drawable您想要随机选择的所有 s 的 ID。

    int[] imageIds = { 
            R.drawable.bg1,
            R.drawable.bg2,
            R.drawable.bg3,
            R.drawable.bg4,
            R.drawable.bg5
            // etc for as many images you have
    };

然后,随机选择其中一个drawableid 并将其设置为ImageButton.

    ImageButton getClickTime = (ImageButton) findViewById(R.id.clicker);
    Random generator = new Random();
    int randomImageId = imageIds[generator.nextInt(imageIds.length)];
    getClickTime.setImageResource(randomImageId);
于 2013-04-14T20:53:41.467 回答
0

如果你想获取资源的 id,你应该使用这样的东西:

    int id = context.getResources().getIdentifier("resource_name", "drawable", context.getPackageName());
     Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), id);
于 2013-04-14T20:20:05.653 回答
0

您可能想要使用所有图像的数组并通过随机索引获取它:

int[] all = {
    R.drawable.bg1,
    R.drawable.bg2,
};
于 2013-04-14T20:21:26.137 回答