2016-08-23 84 views
2

我有,我想设置取决于随机值图像的ImageView的如何在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]图像?

注:我使用的API 22

回答

4

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

在这种情况下,获得资源的名称不一个合适的解决方案,@ pdegand59的答案更容易。 – sagix

+0

@sagix为什么它不适合?解决方案可以是'diceImage.setImageResource(getResources()。getIdentifier(getimages [diceValue],“drawable”,getPackageName());' –

+0

这是比资源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]); 
} 

代替串阵列的创建INT可绘的阵列。所以你可以直接使用它们。

我编辑了你的函数。

1

我只是建议马上使用像毕加索这样的图像加载库。这使得性能变得更好,并且实现起来非常简单。你可以在这里的库: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版本;)

相关问题