我想(从 Activity 继承)通过第二个类访问 ImageView 并更改它。不幸的是,当我尝试这样做时,我得到了 NullPointerExeption。第二个类没有 XML,也没有 onCreate() 方法。它继承自 Activity 只是因为我需要一些功能。
那么如何访问布局或其他组件呢?
这是我第二堂课的代码。
public void changeLoerg() {
int stufe;
//layout = (RelativeLayout)findViewById(R.id.LayoutMain);
imageViewLoerg = (ImageView)findViewById(R.id.imageViewLoerg);
stufe = SettingsLoerg.getLevel(context);
Object tag = imageViewLoerg.getTag();
if (stufe == 1) {
int loergId = R.drawable.animatedegg;
if( tag != null && ((Integer)tag).intValue() == loergId) {
loergId = R.drawable.animatedloerg;
animatedLoerg.stop();
//playAnimationNodelay();
imageViewLoerg.setTag(loergId);
imageViewLoerg.setBackgroundResource(loergId);
playAnimationNodelay();
}
}
}
在 hier das LogCat 下:
01-05 21:34:39.685: W/dalvikvm(9905): threadid=1: thread exiting with uncaught exception (group=0x41b5b300)
01-05 21:34:39.693: E/AndroidRuntime(9905): FATAL EXCEPTION: main
01-05 21:34:39.693: E/AndroidRuntime(9905): java.lang.NullPointerException
01-05 21:34:39.693: E/AndroidRuntime(9905): at android.app.Activity.findViewById(Activity.java:1825)
01-05 21:34:39.693: E/AndroidRuntime(9905): at at.android.dertestloerk.TimerLoerg.changeLoerg(TimerLoerg.java:42)
01-05 21:34:39.693: E/AndroidRuntime(9905): at at.android.dertestloerk.TimerLoerg$1.run(TimerLoerg.java:100)
01-05 21:34:39.693: E/AndroidRuntime(9905): at android.os.Handler.handleCallback(Handler.java:615)
01-05 21:34:39.693: E/AndroidRuntime(9905): at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 21:34:39.693: E/AndroidRuntime(9905): at android.os.Looper.loop(Looper.java:137)
01-05 21:34:39.693: E/AndroidRuntime(9905): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-05 21:34:39.693: E/AndroidRuntime(9905): at java.lang.reflect.Method.invokeNative(Native Method)
01-05 21:34:39.693: E/AndroidRuntime(9905): at java.lang.reflect.Method.invoke(Method.java:511)
01-05 21:34:39.693: E/AndroidRuntime(9905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-05 21:34:39.693: E/AndroidRuntime(9905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 21:34:39.693: E/AndroidRuntime(9905): at dalvik.system.NativeStart.main(Native Method)