正如标题所言,View成员变量已经在Activity的onCreate方法中,通过findViewById方法初始化了。但在另一个类中,用通过new方法构造的Activity对象来执行封装好的公有方法时,发现其中的View成员变量是空的。具体代码如下(new MainActivity().select(selectCity)
这句调用Activity的方法):
错误类型是
错误提示是指向下面这句
然后,调试结果如下
发现这里的View对象是为空的。然后,我换成发送广播的方式,让MainActivity接收广播,这样是可以的,调试结果如下:
发现mCityTextView不是空的。
对比上面的情况,我觉得通过findViewById方法初始化的View对象,只属于Activity这个类本身,所以由它使用是没问题的。但是通过new方法构造的Activity对象,得到的是没有初始化的View对象。所以究竟是怎么回事呢???
怪我咯2017-04-17 17:26:36
The road is a bit wild. new MainActivity() does not follow the Activity life cycle. For example, if you initialize the control in onCreate(), if you call select() directly, it will of course be a null pointer.
伊谢尔伦2017-04-17 17:26:36
Activity, Service, and ContentProvider cannot obtain instances in the new way ("abnormal instances" would be more appropriate). Activity, Service, BroadcastReceiver, and ContentProvider all have life cycles. It is not recommended to use them in Call defined static variables or methods outside the component.
伊谢尔伦2017-04-17 17:26:36
I don’t know if you mean Activity is Android’s Activity component. When constructing the Activity component, you need to execute the attach method and pass in objects such as Context, Window, etc.; I guess the reason why the View is empty is because there is no attach Window object;
Window object It is the container of all Views
PHPz2017-04-17 17:26:36
This is not the activity you want.
Please pass the reference of the activity.
巴扎黑2017-04-17 17:26:36
Look at the code. In fact, you have already written getActivity() before. Just convert the obtained Activity into MainActivity.
Directly new an Activity without using the life cycle method, and this is not the case. Your previous MainActivity
阿神2017-04-17 17:26:36
My problem here is because static is not set for the variable, so when the new object comes out, the variable will be empty and needs to be re-initialized. Uh, I didn’t pass the basic knowledge. . But I still want to thank you for your answers! !