findViewById返回null网上一般都有那2种可能错误的指正,1、在setContentView之前调用了;2、调用LayoutInflater实例化的view1,然后却没有用view1.findViewById而是直接fidnViewById。
但我今天也出了这么个错误,不是这2种情况,而是:
public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public MySurfaceView(Context context, AttributeSet attrs) {
this(context, null, 0);
// TODO Auto-generated constructor stub
}
public MySurfaceView(Context context) {
this(context, null);
// TODO Auto-generated constructor stub
}原本这样设计是为了无论是哪个构造方法,都会走到第一个构造方法去,所以当我在其他地方findViewById这个view的时候,就报空指针了。原来是:
public MySurfaceView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
// TODO Auto-generated constructor stub
}
小问题,记录下来。。。

本文介绍了在使用自定义View时遇到的findViewById返回null的问题及解决方案。通常这种情况由构造方法中的参数传递错误导致。
1万+

被折叠的 条评论
为什么被折叠?



