简体   繁体   English

Android更改ImageButton图像

[英]Android Change ImageButton image

I write an travel APP.There are 20 QR Code in every spot. 我写了一个旅行APP,每个地点都有20个QR码。

When tourist use QR Code scanner scan the QR Code,the ImageButton's image have to change into another image. 当游客使用QR码扫描仪扫描QR码时,ImageButton的图像必须更改为另一张图像。

The problem on this line : spot1.setImageResource(R.drawable.hotspot1); 这行的问题是:spot1.setImageResource(R.drawable.hotspot1);

If I delete this line, there is no problem. 如果删除此行,就没有问题。

I don't know how to fix it. 我不知道该如何解决。

     @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;
   }
  }
 }

Here is my Logcat: http://i.stack.imgur.com/6y2UQ.png 这是我的Logcat: http ://i.stack.imgur.com/6y2UQ.png

You can not initialize any Views from xml before calling setContentView : 在调用setContentView之前,不能从xml初始化任何View:

setContentView(R.layout.hotspot1);
ImageButton spot1=(ImageButton)findViewById(R.id.imageButton1);
spot1.setImageResource(R.drawable.hotspot1);

You are not suppose to call setContentView after setting view resource. 您不应在设置视图资源后调用setContentView call set contentView once in onCreate without setting any view from xml. 只需在onCreate调用一次设置contentView即可,而无需通过xml设置任何视图。

You can then change the layout contents, but do not call setContentView again. 然后,您可以更改布局内容,但不要再次调用setContentView

You are using a image view , but not calling setContentView before it. 您正在使用image view ,但没有在其之前调用setContentView This makes the ImageView as null, hence the error. 这使ImageView为null,因此出现错误。

Try following above suggestions,and it will go. 尝试按照上述建议进行操作,它将成功。 Happy Coding. 编码愉快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM