roid的ImageView的NullPointerExcept

roid的ImageView的NullPointerExcept

本文介绍了Android的ImageView的NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个图像,红灯和绿灯。我有一个自定义的ListView,我想显示红灯时,一个列表项是无效的,而绿灯时,它是积极的。当pressed列表项被激活。

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.

下面是我的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

main.java

ImageView iconLight = (ImageView)findViewById(R.id.iconLight);
iconLight.setImageResource(R.drawable.light_on);

我得到执行设置的图像资源就行了NullPointerException异常。所以,我做了一个小测试,我删除了线路设置的XML文件中的SRC,只是试图将其设置在主类。还是一个NPE。所以,我想在不改变资源,但只是改变了阿尔法。尽管如此NPE。

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.

我不知道我在做什么错。该文件 light_off.png light_on.png 都在 RES /绘,LDPI 和其中任何一个,当我在XML中指定他们的工作。但任何改变我试图做出 iconLight 在主文件导致此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?

推荐答案

要得到就行了NPE的唯一途径...

The only way to get a NPE in the line...

iconLight.setImageResource(R.drawable.light_on);

iconLight 的为空。所以,你的findViewById失败。你已经确立了自己的布局,你打电话之前findViewById?你的确定的R.id.iconLight是在活动的根布局?

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?

这篇关于Android的ImageView的NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 13:44