自定义view时遇到的android.view.InflateException: Binary XML file问题

来源:互联网 发布:玛雅软件是什么 编辑:程序博客网 时间:2024/06/07 16:48

自定义一个view控件,在写完编译成功在手机上运行时老是提示android.view.InflateException: Binary XML file的异常

查看了一遍构造函数书写也是正确,纠结了,于是重新查看了sdk的view构造方法,终于发现了问题所在。从下图可知

public View (Context context)

Added in API level 1

Simple constructor to use when creating a view from code.

Parameters
contextThe Context the view is running in, through which it can access the current theme, resources, etc.
我继承view重写的控件只是重载了这一个构造方法,而从API说明,我们可以看到这个构造方法的view只是适用于从代码创建的view,而需要从xml文件inflate的view则需要重载

public View (Context context, AttributeSet attrs)

这个构造方法,查看sdk我们可以清楚的理解,于是重载后面的构造方法问题解决。

但是为什么呢,主要是因为(AttributeSet attrs)参数其实就是我们需要从xml文件的标签inflate后的xml文件的各种属性,从源码我们可知,构造方法开始时,需要

        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
                defStyleAttr, 0);

TypedArray 即为我们布局的view的属性值数组,有兴趣的可以去查看这段源码,可以大概清楚的了解,view从inflate到加载xml文件数据的基本流程

0 0
原创粉丝点击