我希望(继承自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();
}
}
}
Und 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)
答案 0 :(得分:0)
如果您要修改此View
的类,则应在该类中创建一个方法来修改所述View
。然后,您可以在Activity
中调用该方法,并将您需要的任何内容作为参数传递。
public class BackGround { // please don't extend Activity unless it is one
private ImageView img;
....
public void changeLoerg(int resourceId) {
img.setBackgroundResource(resourceId);
}
}