在Activity的onCreateView 中,有时候发现写的自定义view,通过 findViewById 返回为Null,导致空指针异常。
布局文件中定义
<com.example.qqmediaplayer.view.LyricsView
android:background="@drawable/base_bg"
android:id="@+id/lyricsview"
android:layout_width="wrap_content"
android:layout_height="@dimen/lyricsview_height" >
</com.example.qqmediaplayer.view.LyricsView>
在生成该view的时候,会执行LyricsView的2个参数的构造方法。
public LyricsView(Context context, AttributeSet attrs) {
super(context, attrs);
}
如果 这个时候 这么定义
public LyricsView(Context context, AttributeSet attrs) {
this(context);
}
findViewById 为null, 造成空指针异常 。但是view可以正常显示。
如果 这么写
public LyricsView(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
调用3个参数的构造方法,就没事。
-----------------------------------------
既然view显示,就说明对象已经创建。
猜想调用一个参数的构造方法,创建对象并不是在setContentView之后,因此导致 findViewById 为null? 貌似不对,因为在onClick事件中findViewById 还是null,
因此 调用一个参数构造方法生成的view并不是在DecorView中?
public View findViewById(int id) {
return getWindow().findViewById(id);
}
public View findViewById(int id) {
return getDecorView().findViewById(id);
}