Android崩溃日志

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对象了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值