我试图通过随机数组的drawable来交替线性布局的背景图像,但仍然得到一个空指针异常:
Integer[] images = {R.drawable.image1,R.drawanle.image2};
Random whichImage = new Random();
Int theImage= whichImage.nextInt(1);
View myView= findViewById(R.layout.splash);
myView.setBackgroundResource
(imageSelection[theImage]);
setContentView(myView);
空指针出现在myView.setBackground
.....
干杯.....
答案 0 :(得分:2)
您无法将int传递给后台资源。
而不是
myView.setBackgroundResource(imageSelection[theImage]);
试
myView.setBackgroundResource(getResources().getDrawable(imageSelection[theImage]));
答案 1 :(得分:1)
替换
Integer[] images =
{R.drawable.image1,R.drawanle.image2};
用这个
int[] images = new int[] {R.drawable.image1,R.drawanle.image2};
答案 2 :(得分:1)
Integer[] images = {R.drawable.image1,R.drawanle.image2};
Random whichImage = new Random();
Int theImage= whichImage.nextInt(1);
setContentView(R.Layout.splash);
View myView= findViewById(R.id.view);
myView.setBackgroundResource (imageSelection[theImage]);
答案 3 :(得分:1)
//Should this
Int theImage= whichImage.nextInt(1);
// be replaced with
Int theImage= whichImage.nextInt(images.length);
//Then move your setBackgroundResource call to after you call the setContentView method.
setContentView(myView);
myView.setBackgroundResource(image[theImage]);
答案 4 :(得分:1)
谢谢,我的View myView参考文件有问题,我认为这是返回null。当我使用它来获得背景时它运行良好:
this.getWindow().setBackgroundDrawableResource(imageSelection[theImage]);