以编程方式设置ImageView Drawable

时间:2014-02-23 16:09:12

标签: android imageview

我正在尝试以编程方式从一个drawable数组中设置ImageView的图像但是仍然得到一个NUllPointerException ....这个方法对于设置Image资源是否正确..

//get a random drawable
int[] imageSelection= {R.drawable.buddycheck, R.drawable.logdive3, R.drawable.sea, R.drawable.weather, R.drawable.logo1};
Random whichImage = new Random();
int theImage = whichImage.nextInt(imageSelection.length);

displayImage.setBackgroundResource(theImage);

2 个答案:

答案 0 :(得分:3)

您正在将图像资源设置为随机数。 你需要这样做:

int theImage = imageSelection[whichImage.nextInt(imageSelection.length)];
displayImage.setBackgroundResource(theImage);

答案 1 :(得分:0)

尝试一下:imageView.setImageResource(R.drawable.image);