Android(安卓)自定义Dialog时出现成员变量为null的问题
16lz
2022-06-16
因为项目需要,重写了Android的Dialog,代码如下:
public abstract class BaseExpandDialog extends Dialog {protected Context context;/** * 扩展对话框监听器 */protected BaseExpandDialogClickListener baseDialogClickListener;public BaseExpandDialog(Context context,int contentResId) {// TODO Auto-generated constructor stubsuper(context, R.style.Theme_Mike_BaseDialog);this.context = context;setContentView(contentResId);initialResource();initView();}
其中initialResource()是,设置对话框的宽高,initView()是一个虚函数,申明为abstract需要在子类中实现。然后自定义一个ItemsDialog继承与BaseExpandDialog
其构造函数代码:
protected TextView titleTv = null; public ItemsDialog(Context context) {super(context, R.layout.items_dialog);// TODO Auto-generated constructor stub}
在之类的initView中实现了控件的初始化:
titleTv = (TextView) findViewById(R.id.title_text);然后使用自定义的ItemsDialog:
ItemsDialog dialog = new ItemsDialog(context);dialog.setTitle(list.get(position).getName(),context.getResources().getColor(R.color.text_highlight_color));
ItemsDialog的setTitle就是调用的titleTv.setText的方法
关键问题出现了,titleTv怎么为null,已经initView中已经赋值了,进行调试的时候,也确实在InitView中赋值了
最后发现一个问题initView实在父类的构造函数中进行调用的,而Items的非static的成员变量赋值是,发生在自己的构造函数中。在ItemsDialog的构造函数中,会先执行super()或者this() (如果有的话)->然后在执行自身的非static成员变量的赋值操作->最后才是自己写在构造函数里面的逻辑操作(// TODO Auto-generated constructor stub下的语句),所以现在知道了为什么titleTv为null了,因为先执行了super()父类的构造函数,调用initView对titleTv进行了初始化,然后再调用的自身成员变量的赋值操作titleTv = null;我们现在只需要将protected TextView titleTv = null; 改成protected TextView titleTv;即可
参考: http://www.zhihu.com/question/20616186
更多相关文章
- Android:获取网页源代码
- android 读取SD卡或者其他地方文件功能函数
- Rexsee API介绍:Android屏幕锁定,Keyguard函数与扩展源码
- Android中处理崩溃异常
- Android(安卓)Camera 使用小结
- Android应用程序组件Content Provider的共享数据更新通知机制分
- WiFi流程
- Android系统源码阅读(18):Android(安卓)应用的显示
- 箭头函数的基础使用