在写自定义控件的时候遇到过这个异常,当初一直没搞清楚问题所在,起初代码如下:
public class IndicatorView extends View {
private Paint mPaint;private Path mPath;private float step = 1.0f;public IndicatorView(Context context) {super(context);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int withMode = MeasureSpec.getMode(widthMeasureSpec);int heightMode = MeasureSpec.getMode(heightMeasureSpec);int withSize = MeasureSpec.getSize(widthMeasureSpec);int heightSize = MeasureSpec.getSize(heightMeasureSpec);L.e("onMeasure-->"+"withMode:"+withMode+" ---withSize:"+withSize);setMeasuredDimension(100,100);}
}
乍一看没啥问题,因为这个控件是直接在布局文件中引用的,于是我在上面的构造函数中打了一个log,但运行才发现这个构造函数并没有走;于是我加上了`public IndicatorView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}这个构造函数,就没有报这个错误了,打印日志也发现这个构造函数有运行。
原来之前的错误是因为缺少属性资源集合 AttributeSet,没有了它,自定义控件就找不到它需要的属性资源,因此报错。所以,当在布局文件中引用自定义控件至少要实现这个构造函数。如果只是在代码中直接调用只需要实现带context参数的构造函数。