android - 如何在 ImageView 中设置运行时决定的图像?

标签 android image

我有一个 ImageView,我想在其中根据随机值设置图像

我所知道的是我可以设置这样的图像

 public void onRollClick(View view) {
    String[] images={"dice1.png","dice2.png","dice3.png","dice4.png","dice5.png","dice6.png"};
    int diceValue=new Random().nextInt(6);
    ImageView diceImage= (ImageView) findViewById(R.id.imageView);
    diceImage.setImageResource(R.drawable.dice5);
}

onClick 方法在点击 Button 时被调用。所有图像都在 drawable 目录中。目前,我总是设置图像 dice5.png。我该如何设置 images[diceValue] image?

注意:我使用的是 API 22

最佳答案

您可以简单地存储资源的 ID!

public void onRollClick(View view) {
    int[] images= {R.drawable.dice1, R.drawable.dice2, R.drawable.dice3, R.drawable.dice4, R.drawable.dice5, R.drawable.dice6};
    int diceValue=new Random().nextInt(6);
    ImageView diceImage= (ImageView) findViewById(R.id.imageView);
    diceImage.setImageResource(images[diceValue]);
}

关于android - 如何在 ImageView 中设置运行时决定的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104088/

相关文章:

android - 从 Json 对象 Android 中获取字符串值

android - (Android View )海拔是绝对的还是相对于父级的?

android - 如何使用 adjustPan 滚动布局

python - 在Python中根据条件替换图像像素颜色

image - Delphi中如何获取图像文件的尺寸?

android - 如何为查看寻呼机选择适配器?

java - 我的适配器不会更新值,直到我返回然后再次返回该 Activity 。什么原因

android - 使用 Spinner 开始一个新的 Activity

jquery - 我需要根据窗口宽度更改 img

java - 如何在jsp页面中显示图片?