Android ImageView NullPointerException
我有两个图像,一个是红灯,一个是绿灯。我有一个自定义 ListView,我想在列表项处于非活动状态时显示红灯,在列表项处于活动状态时显示绿灯。按下时会激活列表项。
这是我的代码
row.xml
<ImageView
android:id="@+id/iconLight"
android:src="@drawable/light_off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
main.java
ImageView iconLight = (ImageView)findViewById(R.id.iconLight);
iconLight.setImageResource(R.drawable.light_on);
执行设置图像资源的行时出现 NullPointerException 。所以我做了一些测试,我删除了 XML 文件中设置 src 的行,并尝试在主类中设置它。仍然是NPE。所以我尝试不改变资源,而只是改变alpha。还是NPE。
我不确定我做错了什么。文件 light_off.png
和 light_on.png
都位于 res/drawable-ldpi
中,当我在 XML 中指定它们时,它们中的任何一个都可以工作。但是我尝试对主文件中的 iconLight
进行的任何更改都会导致此 NPE。有什么想法吗?
I have two images, a red light and a green light. I have a custom ListView that I would like to display a red light when a list item is inactive, and a green light when it is active. A list item is activated when it is pressed.
Here is my code
row.xml
<ImageView
android:id="@+id/iconLight"
android:src="@drawable/light_off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
main.java
ImageView iconLight = (ImageView)findViewById(R.id.iconLight);
iconLight.setImageResource(R.drawable.light_on);
I get a NullPointerException executing the line that sets the image resource. So I did a little testing, I deleted the line setting the src in the XML file and just tried to set it in the main class. Still a NPE. So I tried not changing the resource, but just changing the alpha. Still NPE.
I'm not sure what I'm doing wrong. The files light_off.png
and light_on.png
are both in res/drawable-ldpi
and either of them work when I specify them in the XML. But any change I attempt to make to iconLight
in the main file causes this NPE. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在该行中获取 NPE 的唯一方法...
是将 iconLight 设置为 null。所以,你的 findViewById 失败了。您在调用 findViewById 之前设置了布局吗?您确定 R.id.iconLight 位于 Activity 的根布局中吗?
The only way to get a NPE in the line...
Is for iconLight to be null. So, your findViewById is failing. Have you set your layout before you call findViewById? Are you sure R.id.iconLight is in the Activity's root layout?
我也有同样的问题。这是帮助我理解的代码。它适用于对话框窗口,但也可能对您有帮助。
观察最后一行之前的线路。注意它是如何实例化 ImageView 的。
无论如何,对图像的每次更改都是在 setContentView 之后进行的。
I had the same problem. Here is a code that helped me understand. It is for a Dialog window but might help you too.
Watch the line before the last one. Notice how it instantiates the ImageView.
Anyway every change to the image is made after the setContentView.