Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/200.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在ImageView中设置运行时决定的图像?_Android_Image - Fatal编程技术网

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

Android 如何在ImageView中设置运行时决定的图像?,android,image,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= (I

我有一个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
方法。所有图像都位于
drawable
目录中。目前,我总是设置image
dice5.png
。我如何设置,
images[diceValue]
image


注意:我使用的是API 22

您可以使用
getResources().getIdentifier()
从资源名称获取和标识。
此处和此处的更多信息

您只需存储资源的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]);
}
创建int-drawables数组,而不是字符串数组。所以你可以直接使用它们


我已经编辑了你的函数。

我只是建议马上使用像毕加索那样的图像加载库。这使得性能大大提高,而且实现起来非常简单。您可以在此处获取库:这将是您的代码:

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);
    Picasso.with(this).load(images[diceValue]).into(diceImage);
}

编辑:您肯定应该提高您的API版本;)

在这种情况下,按名称获取资源不是一个合适的解决方案,@pdegand59的答案更简单。@sagix为什么不合适?解决方案可以是
diceImage.setImageResource(getResources().getIdentifier(getimages[diceValue],“drawable”,getPackageName());
它比资源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);
    Picasso.with(this).load(images[diceValue]).into(diceImage);
}