自定义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.
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.
看描述,可以看出,当要加载xml布局时,就要调用第二个构造方法。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值