2019年5月23日
引入自定义View直接崩溃,日志提示android.view.InflateException: Binary XML file line #11: Error inflating class ...
原因是自定义View类中没有
View(Context context, AttributeSet attrs) //Constructor that is called when inflating a view from XML
View(Context context, AttributeSet attrs, int defStyle) //Perform inflation from XML and apply a class-specific base style
这两个构造函数,从文档上的介绍来看,第二个和第三个构造函数对于XML这种引用方式是必须实现的,这三个构造函数应该是在不同的应用场合来实例化
在自定义View类中加上这两个方法就好了:
public View(Context context, AttributeSet attrs){
//Constructor that is called when inflating a view from XML
super(context, null);
}
public View(Context context, AttributeSet attrs, int defStyle){
//Perform inflation from XML and apply a class-specific base style
super(context, null);
}
绿色的View改成zidingyiView的类名;
增加这两个构造函数后在Activity中引用自定义View,又发现不能通过findViewById获取到此View对象,日志报空指针异常。
修改构造函数后解决问题,修改如下:
Context mContext;
public View(Context context) {
super(context);
mContext = context;
}
public View(Context context, AttributeSet attrs){
//Constructor that is called when inflating a view from XML
super(context, attrs);
mContext = context;
}
这样就能正常引用自定义View对象了。