自定义view 重写一个构造函数报错的问题

CharView只重写了一个构造函数。

public ChartView(Context context)
{
    super(context);
}
在xml文件中,<com.example.chartview.ChartView />

mainactivity中用findviewbyid实例了ChartView。

结果出现下面错误:

Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class com.example.chartview.ChartView


之后,将其他两个构造函数添加上了,问题就解决了。

public ChartView(Context context, AttributeSet attrs)
{
	super(context, attrs);
}
经测试,只需要添加上面这个构造方法就可以了。
public ChartView(Context context, AttributeSet attrs, int defStyleAttr)
{
	super(context, attrs, defStyleAttr);
}

那这是为什么呢?。。。。。。


先看一下文档:

public View (Context context)

Added in  API level 1

Simple constructor to use when creating a view from code.

Parameters
context The Context the view is running in, through which it can access the current theme, resources, etc.

public View (Context context, AttributeSet attrs)

Added in  API level 1

Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet.

The method onFinishInflate() will be called after all children have been added.

Parameters
context The Context the view is running in, through which it can access the current theme, resources, etc.
attrs The attributes of the XML tag that is inflating the view.
See Also
  • View(Context, AttributeSet, int)

public View (Context context, AttributeSet attrs, int defStyleAttr)

Added in  API level 1

Perform inflation from XML and apply a class-specific base style. This constructor of View allows subclasses to use their own base style when they are inflating. For example, a Button class's constructor would call this version of the super class constructor and supply R.attr.buttonStyle for defStyle; this allows the theme's button style to modify all of the base view attributes (in particular its background) as well as the Button class's attributes.

Parameters
context The Context the view is running in, through which it can access the current theme, resources, etc.
attrs The attributes of the XML tag that is inflating the view.
defStyleAttr An attribute in the current theme that contains a reference to a style resource to apply to this view. If 0, no default style will be applied.
See Also
  • View(Context, AttributeSet)
看描述,可以看出,当要加载xml布局时,就要调用第二个构造方法。

那什么时候是不加载xml布局呢,就是new ChartView(context)方式实例化ChartView时,只会调用第一个构造,不需要第二个构造。

你可能感兴趣的:(自定义view 重写一个构造函数报错的问题)