Android ImageView 空指针异常

标签 android android-widget image-manipulation android-layout

我有两张图片,红灯和绿灯。我有一个自定义 ListView,我想在列表项处于非 Activity 状态时显示红灯,在列表项处于 Activity 状态时显示绿灯。按下时激活列表项。

这是我的代码

行.xml

<ImageView
    android:id="@+id/iconLight"
    android:src="@drawable/light_off"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

主.java

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

我在执行设置图像资源的行时得到一个 NullPointerException。所以我做了一些测试,删除了 XML 文件中设置 src 的行,并尝试在主类中设置它。还是NPE。所以我尝试不更改资源,而只是更改 alpha。仍然是 NPE。

我不确定我做错了什么。文件 light_off.pnglight_on.png 都在 res/drawable-ldpi 中,当我在 XML 中指定它们时,它们都可以工作.但是我尝试对主文件中的 iconLight 进行的任何更改都会导致此 NPE。有什么想法吗?

最佳答案

在队列中获得 NPE 的唯一方法...

iconLight.setImageResource(R.drawable.light_on);

iconLight 为空。因此,您的 findViewById 失败了。在调用 findViewById 之前设置布局了吗?您确定 R.id.iconLight 在 Activity 的根布局中吗?

关于Android ImageView 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4393976/

相关文章:

android - 在 android 4.0.3 上 react native 。可能的?

c++ - 在 C++ 中对 JPEG 的无损操作

python - 如何将图像的像素值复制到另一个python变量以使该python变量将图像保存在opencv中

python - 在 Jython/Python 中复制图片时,如何每行少复制 X 像素

android - 使用 soundpool 和 setOnLoadCompleteListener 的问题

android - 在不使用 GPS 的情况下查找手机的当前位置

java - Realm 和 jackOptions Java 以非零退出值 1 完成 - Android Gradle

android - 使用 Android 在 Canvas 上添加图像

android - 如何在 AlertDialog 中显示 CalendarView?

android - 如何使大图像可点击不同的不同图像部分