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

3
我是一位有用的助手,可以为您翻译文本。
我有一个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);
}

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

注意:我正在使用 API 22。

4个回答

5
您可以简单地存储您资源的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]);
}

1

我建议立即使用像Picasso这样的图片加载库。这可以显著提高性能,并且非常容易实现。您可以在此处获取该库:http://square.github.io/picasso/,以下是您需要使用的代码:

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版本 ;)

0

1
在这种情况下,按名称获取资源不是一个合适的解决方案,@pdegand59的答案更简单。 - sagix
@sagix 为什么不适合?解决方案可以是 diceImage.setImageResource(getResources().getIdentifier(getimages[diceValue],"drawable",getPackageName()); - an_droid_dev
这是比资源ID列表更复杂的解决方案。 - sagix

0
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]);
}

不要使用字符串数组,而是创建一个整数可绘制数组,这样你就可以直接使用它们。

我已经编辑了你的函数。


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