[英]Android Change ImageButton image
我写了一个旅行APP,每个地点都有20个QR码。
当游客使用QR码扫描仪扫描QR码时,ImageButton的图像必须更改为另一张图像。
这行的问题是:spot1.setImageResource(R.drawable.hotspot1);
如果删除此行,就没有问题。
我不知道该如何解决。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (0 == requestCode && null != data && data.getExtras() != null) {
String result = data.getExtras().getString("la.droid.qr.result");
int spotnum=Integer.valueOf(result);
switch(spotnum){
case 1:
ImageButton spot1=(ImageButton)findViewById(R.id.imageButton1);
spot1.setImageResource(R.drawable.hotspot1);
setContentView(R.layout.hotspot1);
break;
case 2:
setContentView(R.layout.hotspot2);
break;
}
}
}
这是我的Logcat: http ://i.stack.imgur.com/6y2UQ.png
在调用setContentView之前,不能从xml初始化任何View:
setContentView(R.layout.hotspot1);
ImageButton spot1=(ImageButton)findViewById(R.id.imageButton1);
spot1.setImageResource(R.drawable.hotspot1);
您不应在设置视图资源后调用setContentView
。 只需在onCreate
调用一次设置contentView即可,而无需通过xml设置任何视图。
然后,您可以更改布局内容,但不要再次调用setContentView
。
您正在使用image view
,但没有在其之前调用setContentView
。 这使ImageView
为null,因此出现错误。
尝试按照上述建议进行操作,它将成功。 编码愉快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.